我在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对象
旁注:手册上说:
对数组进行编码时,如果键不是从0开始的连续数字序列,则所有键都将编码为字符串,并为每个键值对显式指定。
但是我的数组是一个连续集,这就是我使用array_fill
的原因。
更新:
重新表述问题:
所需的是一个数组,其索引对应于给定的ID对象。对于每个丢失的ID,该索引处的数组项必须为
null
。
从提供的示例中可以看出,$data
中对象的ID是零索引的,因此我们初始化和数组的长度为max(ID) + 1
,并像以前一样填充它但是和IMHO,我认为这将是对数组数据结构的滥用。如果你的ID中有很大的缺口,你的数组将包含大量的null
s。由于JS没有关联数组,最好的选择是将数组转换为对象(就像PHP在你的例子中所做的那样)。
由于没有给出$data
,这是我想到的最好的:
如果你有一个关联数组,json_encode
通常会返回一个对象,否则,你会得到一个普通的JSON数组。所以你可能想试试这样的东西:
echo json_encode( array_values($return) );
如果您的ID不是连续的,那么count($data)
不会给出您想要的结果。例如,如果$data
具有密钥1、2、3和5;那么array_fill
只会在$return
上给你0-3的键,你最终会得到一个非序列数组。
试试这个:
$return = [];
$length = max(array_keys($data));
$return = array_fill(0, $length, null);