Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Results for json_encode() PHP

If i do this :

$new_arr = array(
0 => 'keyboard',
1 => 'mouse',
2 => 'computer'
);

print_r(json_encode($new_arr));

Output:

["keyboard","mouse","computer"]

But say i fetch all rows of "product" table from my database and i do this :

$product_with_id_map = array();
foreach($query as $result) {
$product_with_id_map[$result->id] = $result->name;
}
print_r(json_encode($product_with_id_map));

Output:

{"0":"Keyboard","1":"mouse","2":"computer"}

I really need to retain the key of the array when i json_encode also can you tell me how to achieve the second output in the 1st example ?

like image 953
Nishant Jani Avatar asked Sep 24 '12 09:09

Nishant Jani


People also ask

What is JSON_encode () in Python?

Like the reference JSON encoder, json_encode () will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, int, float or bool as an input value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

Which function is used to encode a value to JSON format?

The json_encode () function is used to encode a value to JSON format. Required. Specifies the value to be encoded Optional.

How to JSON_encode a multidimensional array in PHP?

When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example: $arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4)); json_encode($arrytest) gives a single array of multiple json objects.

What are the requirements for JSON in PHP?

Can be any type except a resource . All string data must be UTF-8 encoded. PHP implements a superset of JSON as specified in the original » RFC 7159 .


2 Answers

Use the options (since PHP 5.3):

print_r(json_encode($product_with_id_map, JSON_FORCE_OBJECT));
like image 173
dan-lee Avatar answered Sep 30 '22 15:09

dan-lee


Cast the array to object.

$new_arr = array(
  0 => 'keyboard',
  1 => 'mouse',
  2 => 'computer'
);

print_r(json_encode((object)$new_arr));
// output: {"0":"keyboard","1":"mouse","2":"computer"}

Addtion: If you use this result in javascript, I suggest you use the array, array is also object in javascript, besides, it provide more methods and length property to you.

like image 31
xdazz Avatar answered Sep 30 '22 15:09

xdazz