代码之家  ›  专栏  ›  技术社区  ›  Nick Roberts

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

  •  2
  • Nick Roberts  · 技术社区  · 8 年前

    因此,我有一个web应用程序,我正在尝试创建它,我必须使用odbc\u exec收集两个不同查询的结果,然后创建一个JSON文件,其中包含两个查询的组合信息。

    下面的示例 (省略连接和查询)

    $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\u fetch\u数组会从结果集中删除数据,这就是为什么我试图创建一个对结果集的引用,在每次大循环后重置,但这仍然无法解决我的问题。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Jeff Puckett    8 年前

    $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);