Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a PHP array into json string

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?

like image 268
user3132858 Avatar asked Sep 19 '26 07:09

user3132858


1 Answers

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]);
like image 178
Nigel Ren Avatar answered Sep 21 '26 19:09

Nigel Ren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!