If I do this:
$new_arr = array( 0 => 'keyboard', 1 => 'mouse', 2 => 'computer' ); print_r(json_encode($new_arr));
Conclusion:
[“keyboard”, “mouse”, “computer”]
But I will say that I retrieve all the rows of the "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));
{"0": "Keyboard", "1": "mouse", "2": "computer"}
I really need to save the array key, when I json_encode can also tell me how to achieve the second output in the first example?
Passing an array to an 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: javascript, , javascript, , length.
length
( PHP 5.3):
print_r(json_encode($product_with_id_map, JSON_FORCE_OBJECT));
This is because the indexes returned from the database are returned as strings and therefore are also encoded in JSON. Where, when you create the array yourself, you set them as integers, and therefore they are ignored.
You can try
$new_arr = array( '0' => 'keyboard', '1' => 'mouse', '2' => 'computer' ); print_r(json_encode($new_arr));
or you can throw an array into an object that stores indexes.
print_r(json_encode((object)$new_arr));