Peter Chung Peter Chung - 5 months ago 11
JSON Question

creating a json object inside json object using php efficiently

I'm trying to make a json object inside the json object.
The json object I desire to make is:

{"post1" : {"id" : "1", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
"post2" : {"id" : "2", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
"post3" : {"id" : "3", "brand" : "brandFromQuery", "model" : "modelFromQuery"},
"post4" : {"id" : "4", "brand" : "brandFromQuery", "model" : "modelFromQuery"}}"


What I ultimately want to do is create a json object as you see above and pass it along to the front end. And the data is the result of SQL query. Each "inner" json object is fetched from the query. Any tip on how I should create this?
Would love some efficient solutions for this. I was thinking of doing for loop in a for loop but concerned about the efficiency.

EDIT:
I'm trying to use json_encode to achieve this but i'm not sure how to implement this. what i have tried so far is
1) Create JSON object using PHP
(creates a class and inputs the data). I really like this method because it is creating a separate class so its more modular but i just cant seem to find a way to create 4 different posts.

Answer

If each inner object is a result-set from the SQL query then you just need single for-loop to create kind of JSON string.

Create main array

$main_array=array();

Now iterate over result from MySQL like this and append them in main array.

/* Your MySQL logic to fetch result */
$count=1;
while($row = $result->fetch_assoc()) { // assuming fetch method, you can replace it with yours.
     $main_array["post".$count]=$row;
     $count++;
}

$json_string=json_encode($main_array);

I think this is the best solution in which you can create the required JSON string.

Comments