我在 PHP 中有一个数组,其中包含一个对象列表:
// This is a var_dump of $data
array(3911) {
[0]=>
object(stdClass)#44 (3) {
["ID"]=>
string(1) "1"
["name"]=>
string(9) "Forest"
}
[1]=>
object(stdClass)#43 (3) {
["ID"]=>
string(1) "2"
["Name"]=>
string(3) "Lt. Dan"
}
// etc ...
}
我正在将该数组转换为基于平面索引的数组:
$return = [];
$length = count($data);
$return = array_fill(0, $length, null);
// Convert list into flat array
foreach ( $data as $item ){
$return[(int)$item->ID] = $item->name;
}
header( 'Content-Type: application/json' );
echo json_encode( $return );
我使用 json_encode
得到的结果是一个对象列表:
{"0":null,"1":"Forest","2":"Lt. Dan","3":"Bubba","4":"Jenny"}
我期望得到的是:
[null,"Forest","Lt. Dan","Bubba","Jenny"]
如何让 json_encode
返回 Javascript 数组而不是 Javascript 对象?
旁注:The Manual says那:
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
但我的数组是一个连续的集合,这就是我使用 array_fill
的原因。
最佳答案
更新:
重新表述问题:
desired is an array for which indices correspond to IDs of given objects. For every missing ID, the array item at that index must be
null
.
从提供的示例中可以看出,$data
中对象的 ID 是从零开始索引的,因此我们初始化数组,长度为 max(ID) + 1
并像之前一样填写它。 但是 恕我直言,我认为这将是对数组数据结构的误用。如果您的 ID 有很大的间隔,您的数组将包含大量的 null
。由于 JS 没有关联数组,因此最好的选择是将数组转换为对象(如 PHP 在您的情况下所做的那样)。
由于未给出 $data
,这是我想出的最好的方法:
如果您有关联数组,通常 json_encode
会返回一个对象,否则,您将得到一个普通的 JSON 数组。所以你可能想尝试这样的事情:
echo json_encode( array_values($return) );
关于javascript - 如何让 php `json_encode` 返回 Javascript 数组而不是 Javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744850/