json_encode 稀疏 PHP 数组作为 JSON 数组,而不是 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11195692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
json_encode sparse PHP array as JSON array, not JSON object
提问by Nguyen Van Vinh
I have the following array in PHP:
我在 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:
我想将其 JSON 编码为 JSON 数组,生成如下所示的字符串:
[
{
"id":0,
"name":"name1",
"short_name":"n1"
},
{
"id":2,
"name":"name2",
"short_name":"n2"
}
]
But when I call json_encodeon this array, I get the following:
但是当我调用json_encode这个数组时,我得到以下信息:
{
"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_encodeto encode my array as an array, instead?
我怎样才能json_encode将我的数组编码为一个数组?
回答by Nguyen Van Vinh
You are observing this behaviour because your array is not sequential - it has keys 0and 2, but doesn't have 1as a key.
您正在观察这种行为,因为您的数组不是连续的 - 它有键0和2,但没有1作为键。
Just having numeric indexes isn't enough. json_encodewill only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...
仅有数字索引是不够的。json_encode如果您的 PHP 数组是连续的,也就是说,如果它的键是 0, 1, 2, 3, ...
You can reindex your array sequentially using the array_valuesfunction to get the behaviour you want. For example, the code below works successfully in your use case:
您可以使用该array_values函数按顺序重新索引数组以获得所需的行为。例如,以下代码在您的用例中成功运行:
echo json_encode(array_values($input)).
回答by Boris Guéry
Arrayin JSONare indexed array only, so the structure you're trying to get is not valid Json/Javascript.
ArrayinJSON是仅索引数组,因此您尝试获取的结构不是有效的 Json/Javascript。
PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.
PHP 关联数组是 JSON 中的对象,因此除非您不需要索引,否则无法进行此类转换。
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"],
]
回答by Y0Gi
Try this,
尝试这个,
<?php
$arr1=array('result1'=>'abcd','result2'=>'efg');
$arr2=array('result1'=>'hijk','result2'=>'lmn');
$arr3=array($arr1,$arr2);
print (json_encode($arr3));
?>
回答by Robert Sinclair
json_decode($jsondata, true);
json_decode($jsondata, true);
trueturns all properties to array (sequential or not)
true将所有属性转换为数组(顺序或非顺序)

