(PHP) How to Prevent Discarding of an ODBC Result Set?

本小妞迷上赌 提交于 2019-12-24 02:33:21

问题


So I have a web app that I'm trying to create where I have to use odbc_exec to gather the results of two different queries and then create a JSON file with combined info from the two queries.

Example below (connection and query omitted)...

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

The problem with this is that it stops going into the nested while loop after the first loop through. I know that odbc_fetch_array removes the data from the results set which is why I attempted to create a reference to the result set that resets after each big loop, but that still doesn't resolve my problem.

Any info would be extremely helpful! Thanks in advance!


回答1:


$tempResult = $result1; does not make a deep copy of the object, just a copy by reference to the original object, so when you later call odbc_fetch_array($tempResult) it's really the same thing as odbc_fetch_array($result1) which means you only ever have one object. So any subsequent calls to odbc_fetch_array will be exhausted on either variable. You could clone the object each time, but I think a much more efficient approach would be to iterate through it once and save the values to an array. Then you could re-iterate over the array in your nested loop.

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


来源:https://stackoverflow.com/questions/46328974/php-how-to-prevent-discarding-of-an-odbc-result-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!