Get JSON returned from PHP ADO connection to MS-Access DB

人盡茶涼 提交于 2019-12-25 09:44:50

问题


I'm trying to get JSON string returned from MS-Access DB Query. I get the recordset ($rs) fine, but trying to loop through to return JSON, without knowing all the fields in recordset. The following returns what I want but in [["aaa":"bbb","ccc":"ddd"]] not the [{ ... }] i'm looking for.

    $num_columns = $rs->Fields->Count ();
//echo $num_columns . "<br>";

$arrColumns = array();
for ($i=0; $i < $num_columns; $i++) {
    $arrColumns[] = $rs->Fields($i);
}

$arrResult = array();

while (!$rs->EOF) {
    $arrRow = array();
    for ($i=0; $i < $num_columns; $i++) {
        $arrRow[] = $arrColumns[$i]->value;
    }
    $arrResult[] = $arrRow;
    $rs->MoveNext();
}
//var_dump($arrResult);
echo json_encode($arrResult);
//print_r($arrResult);

[UPDATE]:

accomplished the dynamic part but still have issue with results. Since i'm json_encode($Array) i'm not able to get results with my JQuery as I would like.

$num_columns = $rs->Fields->Count ();
$arrColumns = array();

for ($i=0; $i < $num_columns; $i++) {
    $arrColumns[] = $rs->Fields($i);
    $newArr[] = $rs->Fields($i)->name; 
}

$arrResult = array();

while (!$rs->EOF) {
    $arrRow = array();
    for ($i=0; $i < $num_columns; $i++) {
       $arrRow[$newArr[$i]] = $arrColumns[$i]->value;
    }
    $arrResult[] = $arrRow;

    $rs->MoveNext();
}

echo $_GET['callback'] . '(' . json_encode($arrResult) . ')';

My JSON gets returned like: [{"First":"John"},{"Last":"Doe"}] An array wrapped in an object. I need to return either an object or an array so I can handle in my client side like: {"First":"John"},{"Last":"Doe"}

    <script>
        $.getJSON('http://remote.domain.com/json.php?callback=?',function(res){
            alert('Results: '+res.Last);
        });
    </script>

I think it might be the way I'm json_encode($Array); and not using a class?


回答1:


If you want to return in the [{...}] format, you will need to change the $arrRow value from array into class. To make it simple, you can leverage the use of stdClass()

Try something like this:

while (!$rs->EOF) {
    $arrRow = array();

    $class = new stdClass();
    $class->field1 = $arrColumns[1]->value;
    $class->field2 = $arrColumns[2]->value;

    $arrRow[] = $arrColumns[$i]->value;

    $arrResult[] = $arrRow;
    $rs->MoveNext();
}

echo json_encode($arrResult);



回答2:


You not not have it in [["aaa":"bbb","ccc":"ddd"]] because its not a valid json array format ... see JSON.ORG for specification

array should be represented as

While Objects

The closet you can have is has array is

[["aaa","bbb"]["ccc","ddd"]]


来源:https://stackoverflow.com/questions/13556544/get-json-returned-from-php-ado-connection-to-ms-access-db

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