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?
If you want to return in the
[{...}]format, you will need to change the$arrRowvalue from array into class. To make it simple, you can leverage the use ofstdClass()Try something like this: