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?

user3132858
  • 609
  • 1
  • 11
  • 27

3 Answers3

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]);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
2

If you do something like:

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

this will give you the output you require.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
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])
Eugene
  • 1,690
  • 3
  • 16
  • 30