Home » Php » PHP json_encode return rows as objects instead of arrays

PHP json_encode return rows as objects instead of arrays

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am using json_encode() to encode array into json format. but it returning object instead of array. I want to return an array not an object.
any body have any idea?

How to&Answers:

Basically json_decode() will return two types of data.

1) Object 
2) Associative array

By default, json_decode() returns object type value.

But, if you want value as an array format you must use TRUE as a second argument in json_decode().

e.g,

$decoded_value = json_decode($json_encoded_value, TRUE);

Answer:

You should use json_decode with TRUE param like following example:

$array = array(1,2,3);
$encode = json_encode($array);

$decode = json_decode($encode, TRUE);

Now $decode is array, not object.

Answer:

use this code for decoding your encode json data

$encode = $your_json_encoded_data

json_decode($encode, TRUE);

Answer:

actually json_encode function in php will return a json formatted string.

and if you want to parse json formatted string back in php
then you should use json_decode.

json_decode function will return data two types.
object & associtavie array.

json_decode(); return type object

json_decode(, TRUE); return type associtative array