echology
echology

Reputation: 397

Create a JSON array from MySQL result array for jQuery datatables

I have a mySQL result array in the form such as. If the array is say "$getSessionList"

Array(

[0] =>array(

     [name] => azure

          )
[1] =>array(

     [name] => maroon

          )
)

My objective is to convert this array into JSON array of this format:

{"data": [["azure"],["maroon"]]}

I have used this PHP code to get the result:

$tableData = new stdClass();
$tableData->data = array();

if (count($getSessionList) > 0) {

for ($i = 0; $i < count($getSessionList); $i ++) {
    $getSessionListRecord = $getSessionList[$i];

    $data = new stdClass(); 
    $data->name   = $getSessionListRecord['name'];


    array_push($tableData->data, $data);

     }
}

echo json_encode($tableData);

?>

The above code yields the following result:

{"data": [["name":"azure"],["name":"maroon"]]}

I want this JSON format array:

{"data": [["azure"],["maroon"]]}

But my current code is giving me this JSON array:

{"data": [["name":"azure"],["name":"maroon"]]}

I don't want the keys "name" in the JSON array.

How can I achieve this, any help here will be much appreciated.

Upvotes: 0

Views: 444

Answers (2)

Wizard
Wizard

Reputation: 862

try this:

$tableData = array();
$tableData['data'] = array_map(function($session) {
    // it's a separate session item inside the session_list
    return array($session['name']);
}, $getSessionList);

// any associative array converts to js-object
// it doesn't matter is that an associative array or std-object
echo json_encode($tableData);

Upvotes: 1

Matt Davis
Matt Davis

Reputation: 470

Try something like this:

$tableData = new stdClass();
$tableData->data = array();

if (count($getSessionList) > 0) {

for ($i = 0; $i < count($getSessionList); $i ++) {
    $getSessionListRecord = $getSessionList[$i];

    $data = array($getSessionListRecord['name']);


    array_push($tableData->data, $data);

     }
}

echo json_encode($tableData);

?>

Currently you're creating a new PHP object with this code

$data = new stdClass();

And then you're adding the data to the key name with this line:

$data->name = $getSessionListRecord['name'];

By simply putting the data into an empty array, and pushing that onto your other array you won't have the name key when you convert to JSON.

Upvotes: 2

Related Questions