开发者

json_encode does not print the array name

开发者 https://www.devze.com 2023-04-07 04:17 出处:网络
I\'m not experienced with json_encode and am trying to return an arrray of array which should be called aaData - for DataTables with server-side processing.

I'm not experienced with json_encode and am trying to return an arrray of array which should be called aaData - for DataTables with server-side processing.

The output should be like:

{
    "sEcho": 3,
    "iTotalRecords": 57,
    "iTotalDisplayRecords": 57,
    "aaData": [
        [
            "Gecko",
            "Firefox 1.0",
            "Win 98+ / OSX.2+",
            "1.7",
            "A"
        ],
        [
            "Gecko",
            "Firefox 1.5",
            "Win 98+ / OSX.2+",
            "1.8",
            "A"
        ],
        ...
    ] 
}

but the actuall output of my PostgreSQL 8.4-driven P开发者_Go百科HP-script

if (isset($_REQUEST['json'])) {
    $aaData = array();
    while ($row = $sth->fetch(PDO::FETCH_NUM)) {
        array_push($aaData, $row);
    }
    print json_encode($aaData);
}

is actually missing outside brackets (object like?) and the aaData name:

[
    [ .... ],
    [ .... ],
    [ .... ]
]

How would you do this best?


Another option is to use the code in the question but change one line:

print json_encode(array('aaData' => $aaData));


If you want it to have aaData as the name, then you'll need to give your array an associative index, like so:

if (isset($_REQUEST['json'])) { 
    $arr['aaData'] = array(); 
    while ($row = $sth->fetch(PDO::FETCH_NUM)) { 
        array_push($arr['aaData'], $row); 
    } 
    print json_encode($arr); 
}


To explain the root of your problem: The name of the variable, $aaData, has nothing to do with the data itself. Thus, json_encode does not serialize it.

0

精彩评论

暂无评论...
验证码 换一张
取 消