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

Why would a foreach loop stop after the first iteration on a mysqli result object?

我有一组 mysqli 结果,我正在迭代这些结果以创建嵌套数组,每个嵌套数组中的订单 ID 都相同。

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

mysqli select:

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;
}

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

因为结果集不是数组(尽管它是可迭代的),所以它是一种资源。但是,当您到达结果集的末尾时,您需要在再次迭代之前手动将其重置为开头

第一次检索到 $result 后,您将迭代整个 $ress(减去第一条记录),因此您需要重置结果集指针才能到达下一个 $result,因为 $ress 和 $results 都指向同一个资源。

$count += 1;

之后立即使用 data_seek 将结果集重置回 $count
$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);
}