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 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.
The json_encode () function is used to encode a value to JSON format. Required. Specifies the value to be encoded Optional.
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.
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 .
Use the options (since PHP 5.3):
print_r(json_encode($product_with_id_map, JSON_FORCE_OBJECT));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With