jajtiii Posted June 25, 2006 Share Posted June 25, 2006 In my code, there are many instances (mostly after dB queries) where I am setting a certain object value to an array. For example, I might hit the dB for every flower that blooms in July and create an array called 'flower_names' which has all of the values that were returned.Later on in my script, I will access this object property and assume it is an array, performing various functions that actually require it to be an array. For example, perhaps my user has submitted a request for a certain flower and i want to check to see if THAT flower is also in my dB, so I do the following :[code]if (in_array($user_stuff, $myGarden->flower_names)) {[/code]Now, all of this works fine with one exception. If my query pulls only ONE flower, then the property is not an array and php kicks out an error.I build by arrays like so :[code]$res = [array of row results from db];$ct = [num_rows];for($x=0; $x<$ct; $x++) {if ($res[$x]['flower_color'] = 'red') {$this->flower_name[] = $res[$x]['flower_name'];}}[/code]There's a lot more to it, but hopefully this lays down the idea. I don't want to do 'if is_array'. What I am hoping to get is another coder's method for building arrays to get around this.any thoughts are welcome Quote Link to comment Share on other sites More sharing options...
paul2463 Posted June 25, 2006 Share Posted June 25, 2006 [!--quoteo(post=387723:date=Jun 25 2006, 05:39 AM:name=jajtiii)--][div class=\'quotetop\']QUOTE(jajtiii @ Jun 25 2006, 05:39 AM) [snapback]387723[/snapback][/div][div class=\'quotemain\'][!--quotec--]I build by arrays like so :[code]$res = [array of row results from db];$ct = [num_rows];for($x=0; $x<$ct; $x++) {if ($res[$x]['flower_color'] = 'red') {$this->flower_name[] = $res[$x]['flower_name'];}}[/code][/quote]a better way to build the array I feel is use the while statement instead of a FOR loop.[code]$query = "pull all data from the database that you require";$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());$flower_name = array(); //force it to be an arrayif (mysql_num_rows($result) >0) { while($row = mysql_fetch_assoc($result)) { if ($row['flower_color'] == 'Red') { $flower_name[] = $row['flower_name']; //puts the flower name into the $flower_name array } }}[/code]hope that helps Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.