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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2
Jourdon

集合的操作都不会重置 key,如果需要得到连续key,使用 values就可以了。

$filtered = $collection->where('price', 100)->values();
4年前 评论

@Jourdon 感谢,文档没有详细的看就记着找解决方法了 :grinning:

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!