(PHP)如何防止丢弃ODBC结果集?

(PHP)如何防止丢弃ODBC结果集?

问题描述:

所以我有一个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循环之前检出结果集中的行数,它总是返回相同的值。 –

$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

不错!谢谢杰夫。我也很欣赏这个解释。这不仅有助于这种情况,而且在其他情况下,如果我必须做类似的事情,也不会有所帮助。 –