PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 4, 2022

[FIXED] How to convert a PHP array into json string

 December 04, 2022     arrays, json, jsonencoder, php     No comments   

Issue

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?


Solution

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


Answered By - Nigel Ren
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing