2

I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:

My current code:

while(!$sql_query->EOF){
     $data[] = array(
                'id'                => $id, 
                'name'              => $name,
                'title'             => $title
                );
$sql_query-> MoveNext(); }

echo json_encode($data);

The output I get with my code is this:

[
   {
     "id":"1",
     "name":"Nick",
     "title":"Office"
   },
   {
     "id":"2",
     "name":"Amy",
     "title":"Home"
   }
]

However, I need the outcome to be:

{
  "data": [
    [
      "1",
      "Nick",
      "Office"
    ],
    [
      "2",
      "Amy",
      "Home"
    ]
  ]
}

I tired paying around with array_values() but no success so far.

Can somebody suggest the right approach here?

3 Answers 3

4

When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...

$data = [];
while(!$sql_query->EOF){
    $data[] = [ $id, $name,$title];
    $sql_query-> MoveNext(); 
}

echo json_encode(["data" => $data]);
2

If you do something like:

$result = (object)["data" => $data];
echo json_encode($data);

this will give you the output you require.

2

First of all you have to modify you array

$newData = [];
foreach($data as $item) {
    $newData[] = array_values($item);
}

and then create new array

echo json_encode(["data"=>$newData])

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.