Laravel 集合 where 返回的数据格式问题
where以一对指定的「键/数值」筛选集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
实际运行结果是:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
return response()->json($filtered->all());
/*
// json结果里把索引当做了key
{
"1": {
"product": "Chair",
"price": 100
},
"3": {
"product": "Door",
"price": 100
}
}
// dd后的结果,key不连续了
array:2 [
1 => array:2 [
"product" => "Chair"
"price" => 100
]
3 => array:2 [
"product" => "Door"
"price" => 100
]
]
*/
使用array_values后的结果:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filteredAll = array_values($filtered->all());
dd($filteredAll);
return response()->json($filteredAll);
/*
[
{
"product": "Chair",
"price": 100
},
{
"product": "Door",
"price": 100
}
]
array:2 [
0 => array:2 [
"product" => "Chair"
"price" => 100
]
1 => array:2 [
"product" => "Door"
"price" => 100
]
]
*/
应该和json_encode有关,连续索引0、1、2这样的转换后不转换索引为key,不连续的就会把索引转换为key
所以where查找后需要将数组索引重置
这里使用array_values,也可以使用
$filteredAll = array_merge($filtered, []);
或
$filteredAll = $filtered->all();
sort($filteredAll);
查找后得到结果:
jsonencode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式
比如,现在有一个索引数组
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
结果为:
["one","two","three"]
如果将它改为关联数组:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
结果就变了:
{"1":"one","2":"two","3":"three"}
本作品采用《CC 协议》,转载必须注明作者和本文链接
集合的操作都不会重置
key
,如果需要得到连续key
,使用values
就可以了。@Jourdon 感谢,文档没有详细的看就记着找解决方法了 :grinning: