Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

build json array in php dynamically

Tags:

json

php

I can create simple json objects like this:

$d = array('item' => "$name" ,'rate' => "$rating");

But what if I want to build an array of items and do it dynamically since I am building it from a db query?

Update:

Let me be more specific I know I have to do:

$jsonCode = json_encode($d);

which will create a json object with an item and rate field. But I want multiple json objects in a json array when i encode it.

What I want json wise is something like this:

[{"item":"toy","rating":"baz" },{"item":"bike","rating":"2.3" }, {"item":"juice","rating":"1.3" }]
like image 546
Mike Avatar asked Jun 26 '13 23:06

Mike


3 Answers

But I want multiple json objects in a json array when i encode it.

Then create an array of arrays and pass it to json_encode. The documentation about arrays explains how to add elements to an array, in the section Creating/modifying with square bracket syntax.

Associative arrays, like the one you already have, will be encoded as objects, "normal" arrays (arrays with consecutive numerical keys) will be encoded as arrays.

Example:

$d = array();

// This appends a new element to $d, in this case the value is another array
$d[] = array('item' => "$name" ,'rate' => "$rating");

$json = json_encode($d);
like image 101
Felix Kling Avatar answered Oct 08 '22 05:10

Felix Kling


This will create a multi-dimensional array from your database query, and then encode it as JSON.

$d = array();
while ($row = $stmt->fetch_assoc()) {
  $d[] = $row;
}
$json = json_encode($d);

Each $row will be an associative array of the data returned from the database. Assigning it to $d[] adds it as an indexed element of that container array.

like image 9
Barmar Avatar answered Oct 08 '22 06:10

Barmar


What you can do is create a php array dynamically as you want then covert it into a json array as below.

$json_array = json_encode($array);

Keep in mind that what you have provided is not a json array

like image 1
Techie Avatar answered Oct 08 '22 07:10

Techie