2015-01-13 83 views
0

我有一套mysqli結果,我正在迭代創建嵌套數組與每個嵌套數組中的所有相同的訂單ids。爲什麼foreach循環會在mysqli結果對象的第一次迭代之後停止?

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

有誰知道爲什麼會在第一次迭代後停止?

+0

請結果集重置爲$count,也添加請求碼(SQL) – Spoke44

+0

@ Spoke44,我更新的問題。 – DuckPuncher

回答

2

因爲結果集不是數組(儘管它是可迭代的),它是一個資源。但是,當您到達結果集的末尾時,需要在重新開始之前手動將其重置爲開頭

第一次檢索到$result後,您將遍歷整個$ress(少於第一條記錄),所以您需要重置結果集指針才能進入下一個$result,因爲$ ress和$ results都指向相同的資源。

使用data_seek後立即$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); 
} 
+0

就是這樣!我沒有意識到我必須重置指針。謝謝! – DuckPuncher

+0

這仍然非常難看。首先將記錄提取到一個數組,然後循環就不會再出現問題。 –

相關問題