1

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 PHP-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?

3 Answers 3

11

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

print json_encode(array('aaData' => $aaData));
Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

That gives me {"aaData":null}
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.