How to create a JSON Object in PHP?

JSON or JavaScript Object Notation is a powerful format that’s been used mainly whenever we need to include some kind of dynamic data fetching within our website, using JavaScript. It’s the ideal format when working and communicating with application programming interfaces.

To create a JSON object in PHP you simply call the json_encode() function by passing an array of your choice as parameter. For instance, suppose we have an array of objects that contain an id and a label.
$arr = array([‘id’=>1, ‘label’=>’id1’], [‘id’=>2, ‘label’=>’id2’]). To convert it into a JSON object you simply write: json_encode($arr).

Convert into JSON using json_encode()

$arr = array(
    ['id'=>1, 'label'=>'id1'],
    ['id'=>2, 'label'=>'id2']
);
echo json_encode($arr);
// prints: [{"id":1,"label":"id1"},{"id":2,"label":"id2"}]

If you choose to store the result of json_encode to a variable, in order to use it later you’ll have to decode it back using the corresponding function which is the opposite of encode: json_decode. If you simply decode the stored value, you’ll get back an array of stdClass objects. If you don’t recall what’s an stdClass object, read more here.

Get an array from a JSON object using json_decode()

$arr = array(
    ['id'=>1, 'label'=>'id1'],
    ['id'=>2, 'label'=>'id2']
);
$json = json_encode($arr);
$parsed = json_decode($json);
echo '<pre>';
print_r($parsed);
/* prints:
Array ( 
    [0] => stdClass Object (
        [id] => 1
        [label] => id1
    )
   [1] => stdClass Object (
        [id] => 2
        [label] => id2
    )
) */

In case you want your data in a plain array type, you only have to visit the post regarding stdClass classes and objects. There’s a function there named std_to_array. Use it freely to experiment around and form your own data structure that fulfills a specific use case.