开发者

While loop in foreach loop not looping correctly

开发者 https://www.devze.com 2022-12-30 04:42 出处:网络
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 exp

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 $colu开发者_运维技巧mn){

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


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_...


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号