I have the following array in PHP:
Array
(
[0] => Array
(
[id] => 0
[name] => name1
[short_name] => n1
)
[2] => Array
(
[id] => 2
[name] => name2
[short_name] => n2
)
)
I want to JSON encode it as a JSON array, producing a string like the following:
[
{
"id":0,
"name":"name1",
"short_name":"n1"
},
{
"id":2,
"name":"name2",
"short_name":"n2"
}
]
But when I call json_encode
on this array, I get the following:
{
"0":{
"id":0,
"name":"name1",
"short_name":"n1"
},
"2":{
"id":2,
"name":"name2",
"short_name":"n2"
}
}
which is an object instead of an array.
How can I get json_encode
to encode my array as an array, instead?
Array
in JSON
are indexed array only, so the structure you're trying to get is not valid Json/Javascript.
PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.
If you want to get such structure you can do:
$indexedOnly = array();
foreach ($associative as $row) {
$indexedOnly[] = array_values($row);
}
json_encode($indexedOnly);
Will returns something like:
[
[0, "name1", "n1"],
[1, "name2", "n2"],
]
Try this,
<?php
$arr1=array('result1'=>'abcd','result2'=>'efg');
$arr2=array('result1'=>'hijk','result2'=>'lmn');
$arr3=array($arr1,$arr2);
print (json_encode($arr3));
?>
json_decode($jsondata, true);
true turns all properties to array (sequential or not)
Source: Stackoverflow.com