为什么在mysqli结果对象的第一次迭代后foreach循环会停止?

时间:2015-01-13 14:33:13

标签: php arrays mysqli nested

我有一组mysqli结果,我正在迭代创建嵌套数组,每个嵌套数组中都有相同的顺序ID。

Here is what each record looks like when using <pre>print_r($result)</pre>

mysqli选择:

SELECT s.*, s.id as stopId, o.* FROM stops AS s INNER JOIN orders AS o ON o.id = s.orderId WHERE o.status = 'A' AND scheduledArrivalEarly >= CURDATE() ORDER BY scheduledArrivalEarly ASC, state ASC

这是mysqli结果对象:

mysqli_result Object
(
    [current_field] => 0
    [field_count] => 83
    [lengths] => 
    [num_rows] => 478
    [type] => 0
)

我知道我有多个结果,而我遇到的问题是当我遍历结果对象并开始构造数组时,它只经过1次迭代并停止。

Here is the array structure I expect when using my code to build the nested arrays

我得到了第一个带有该结构的结果,但正如我之前所说,迭代在第一个结果之后停止。

以下是我用来构建嵌套数组的代码:

$ress = $results;
$count = 0;
foreach($results as $result){
    echo $count . "<br>";
    $orderId = $result['orderId'];
    $records[$count] = array();
    foreach($ress as $r){
        if($r['orderId'] == $orderId and !in_array($r, $records[$count])){
            array_push($records[$count], $r);
        }
    }
    $count += 1;
}

有人知道为什么这会在第一次迭代后停止吗?

1 个答案:

答案 0 :(得分:2)

因为结果集不是数组(虽然它是可迭代的),但它是一个资源。但是,当您到达结果集的末尾时,需要手动将其重置为开头,然后再次迭代它

在第一次检索到$result之后,您将遍历整个$ress(少于第一条记录),因此您需要重置结果集指针才能进入下一个$result,因为$ ress和$ results都指向同一个资源。

使用data_seek$count

之后立即将结果集重置为$count += 1;
$ress = $results;
$count = 0;
foreach($results as $result){
    echo $count . "<br>";
    $orderId = $result['orderId'];
    $records[$count] = array();
    foreach($ress as $r){
        if($r['orderId'] == $orderId and !in_array($r, $records[$count])){
            array_push($records[$count], $r);
        }
    }
    $count += 1;
    $results->data_seek($count);
}
相关问题