Reputation: 1993
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 ?
Upvotes: 5
Views: 4662
Reputation: 160833
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.
Upvotes: 6
Reputation: 3773
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));
Upvotes: 3
Reputation: 14492
Use the options (since PHP 5.3):
print_r(json_encode($product_with_id_map, JSON_FORCE_OBJECT));
Upvotes: 8