Tom Brunoli
Tom Brunoli

Reputation: 3466

While loop in foreach loop not looping correctly

I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.

$results = array();

foreach($this->columns as $column){

    $current = array();

    while($row = mysql_fetch_array($this->results)){
        $current[] = $row[$column];
        print_r($current);
        echo '<br><br>';
    }

    $results[$column] = $current;

}

print_r($results);

return mysql_fetch_array($this->results);

This works, but the while loop only works on the first column. The print_r($results); shows the following:

Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )

Can anybody shed some light? Thanks in advance!

Upvotes: 1

Views: 1100

Answers (2)

user97410
user97410

Reputation: 724

I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:

foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value

}

Upvotes: 0

MartinodF
MartinodF

Reputation: 8254

It's because you already fetched every row, and the internal pointer is at the end. The next while, mysql_fetch_array() will immediately return false. You can reset the pointer to the first row:

mysql_data_seek($this->results, 0);

Put this just before

while($row = mysql_...

Upvotes: 4

Related Questions