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 ?
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.
Use the options (since PHP 5.3):
print_r(json_encode($product_with_id_map, JSON_FORCE_OBJECT));
This is happening because the indexes that are being returned from the data base are coming back as strings and so are being encoded in the JSON too. Where as when you're creating the array yourself you're setting them as integers and so they are being ignored.
You could either try
$new_arr = array(
'0' => 'keyboard',
'1' => 'mouse',
'2' => 'computer'
);
print_r(json_encode($new_arr));
or you could trun the array into an object which will preserve the indexes.
print_r(json_encode((object)$new_arr));