NYCPHP Meetup

NYPHP.org

[nycphp-talk] for() question

Dan Cech dcech at phpwerx.net
Tue Apr 20 16:05:04 EDT 2004


Scott Mattocks wrote:
> Rafi Sheikh wrote:
> 
>> Now, It is very embarrassing but after I get the data read in (code 
>> below),
>> I for the love of PHP, can not make unique rows or dynamically assign the
>> data.  I tried the following:
>> $plot=array();
>> $i=0;
>>
>>  while ($row = mysql_fetch_assoc($resultID)) {
>>
>>     foreach($row as $field) {
>>     $plot[$i]=$field;
>>     $i++;
>>     }
> 
> The problem is that $field is a reference. You are assigning the value 
> of $plot[$i] to the refernce $field.  The place that $field points 
> changes with every iteration of the foreach loop.

Actually, that is not what is happening.  The problem is that there are 
2 loops at work here, when only one is necessary.

The outer (while) loop is iterating over the rows in the result as 
expected, but the inner (foreach) loop is then iterating over each field 
in every row, and assigning the value to the $plot array.

Given a table like:

1, test1, hello
2, test2, tiger

You would end up with $plot looking like:

array (
   0 => 1,
   1 => test1,
   2 => hello,
   3 => 2,
   4 => test2,
   5 => tiger
);

When what you really want is:

array (
   0 => array (1, test1, hello),
   1 => array (2, test2, tiger)
);

The simplest way to achieve this is:

$plot = array();
while ($row = mysql_fetch_assoc($resultID)) {
     $plot[] = $row;
}

Dan

> That is why all of your entries in plot end up being the same.  Try this:
> 
>  while ($row = mysql_fetch_assoc($resultID)) {
> 
>      foreach($row as $key => $field) {
>      $plot[$i]=$row[$key];
>      $i++;
>      }
> 
> It isn't the cleanest or most elegant but I think it should work for 
> what you need.
> 
> Scott Mattocks





More information about the talk mailing list