2017-09-20 38 views
2

所以我有一個web應用程序,我試圖創建,我必須使用odbc_exec來收集兩個不同查詢的結果,然後用兩個查詢中的組合信息創建一個JSON文件。(PHP)如何防止丟棄ODBC結果集?

實施例下面(連接和查詢中省略) ...

$result = odbc_exec($c, $q); 
$result1 = odbc_exec($c, $q1); 
$resultRows = array(); 
$response = array(); 

while($row = odbc_fetch_array($result)) { 
    $tempResult = $result1; 
    $value = "0"; 
    $other = $row['FIELD']; 
    while($row1 = odbc_fetch_array($tempResult)) { 
     if($row['FIELD'] == $row1 ['FIELD']) { 
      $value = $row1['FIELD']; 
     } 
    } 
    if($value != "0") { 
     $resultRows[] = array('FIELD'=>$value, 'OTHER'=>$other); 
    } 
} 

$response['data'] = $resultRows; 

$fp = fopen('somefile.json', 'w'); 
fwrite($fp, json_encode($response)); 
fclose($fp); 

的問題是,它停止進入嵌套while循環第一環路通過後。我知道odbc_fetch_array從結果集中刪除數據,這就是爲什麼我試圖創建一個對每個大循環後重置的結果集的引用,但仍然無法解決我的問題。

任何信息將非常有幫助!提前致謝!

+0

將結果集分配給臨時值的方式,我也這樣做,也清除結果集? –

+0

如果我在while循環之前檢出結果集中的行數,它總是返回相同的值。 –

回答

1

$tempResult = $result1;不會使對象的深拷貝,只是拷貝參考原始對象,所以當你再打odbc_fetch_array($tempResult)它是真正爲odbc_fetch_array($result1)同樣的事情,這意味着你永遠只能有一個對象。因此任何後續對odbc_fetch_array的調用都將在任一變量上耗盡。您可以每次使用clone這個對象,但我認爲一個更有效的方法是迭代一次並將值保存到一個數組中。然後你可以重新遍歷嵌套循環中的數組。

$result = odbc_exec($c, $q); 
$result1 = odbc_exec($c, $q1); 
$resultRows = array(); 
$response = array(); 

// save this to a regular array for re-use later 
$innerQueryResult = array(); 
while($rowTemp = odbc_fetch_array($result1)) { 
    $innerQueryResult []= $rowTemp; 
} 

while($row = odbc_fetch_array($result)) { 
    $value = "0"; 
    $other = $row['FIELD']; 

    // iterate through the inner query result set 
    foreach ($innerQueryResult as $row1) { 
     if($row['FIELD'] == $row1 ['FIELD']) { 
      $value = $row1['FIELD']; 
     } 
    } 
    if($value != "0") { 
     $resultRows[] = array('FIELD'=>$value, 'OTHER'=>$other); 
    } 
} 

$response['data'] = $resultRows; 

$fp = fopen('somefile.json', 'w'); 
fwrite($fp, json_encode($response)); 
fclose($fp); 
+1

不錯!謝謝傑夫。我也很欣賞這個解釋。這不僅有助於這種情況,而且在其他情況下,如果我必須做類似的事情,也不會有所幫助。 –