Jump to content


Photo

Using Arrays


  • Please log in to reply
1 reply to this topic

#1 jajtiii

jajtiii
  • Members
  • PipPipPip
  • Advanced Member
  • 43 posts

Posted 25 June 2006 - 10:39 AM

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 :

if (in_array($user_stuff, $myGarden->flower_names)) {

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 :

$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'];
}
}

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

#2 paul2463

paul2463
  • Members
  • PipPipPip
  • Advanced Member
  • 955 posts
  • LocationUK

Posted 25 June 2006 - 12:00 PM

[!--quoteo(post=387723:date=Jun 25 2006, 05:39 AM:name=jajtiii)--][div class=\'quotetop\']QUOTE(jajtiii @ Jun 25 2006, 05:39 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
I build by arrays like so :

$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'];
}
}
[/quote]

a better way to build the array I feel is use the while statement instead of a FOR loop.


$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 array

if (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
       }
   }
}

hope that helps
you cannot affect the past but you can ruin a perfectly good present by worrying about the future

*********************************************************************
The <A HREF="http://www.php.net/d...php">MANUAL</A> is actually a useful resource




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users