我正在 Laravel API 中生成一系列类别和子类别,以便在客户端应用程序中使用。
我通过使用集合的 filter
和 map
方法来组织从数据库中提取的数据来实现此目的:
// get the data from the category table
$categoryData = $categories->all()->categories();
// filter the data by category names we know we want and create the multi-dimensional array of the fields we need
$categoryList = $categoryData->filter(function ($value) {
return $value['Category'] == "by Area of Interest" || $value['Category'] == "by Grade Level";
})
->map(function ($value) {
return ['category' => $value['Category'], 'subCategory' => $value['Subcategory']];
});
dd($categoryList);
当我查看模具和转储结果时,我得到了我的集合,其中包含格式正确的项目数组:
如果我将其输出为数组:
dd($categoryList->toArray());
我看到了我期望的多维数组。
我遇到的问题是当我尝试将其输出为 json 供我的客户端应用程序使用时。
dd($categoryList->toJson());
如果我输出为 json,我会得到一个对象,其中包含 php 数组索引作为属性,以及 php 子数组作为分配给这些属性的对象。
我想要的是一个包含对象数组的 json 对象。例如
$categoryList = [['category' => 'test', 'subCategory' => 'test'], ['category' => 'test', 'subCategory' => 'test']];
dd(json_encode($categoryList));
哪些输出:
我的催收电话有什么问题吗?
更新
根据 Hognbin 的评论:
调用 $categories->all()->categories();
返回类别数据的集合,然后我可以操作该集合来获取列表。
$categoryData = $categories->all()->categories();
dd($categoryData);
产量:
最佳答案
问题是索引是类别的 id,当您尝试从中创建数组时,您将从 eloquent 集合中获得这些类别的 id。
如果你想要一个干净的对象数组,我建议这样做:
json_encode(array_values($categoryList->toArray()));
Chris 最终实现
上面的解释和函数调用得到了我需要的最终结果。在通过这些函数调用确认它有效后,我查看了 Collection 类方法,看看如何使用该类来实现它。这是我所做的:
$categoryList = $categoryData->filter(function ($value) {
return $value['Category'] == "by Area of Interest" || $value['Category'] == "by Grade Level";
})
->map(function ($value) {
return ['category' => $value['Category'], 'subCategory' => $value['Subcategory']];
})
->values()
;
如果您查看 Collection
类的 values()
方法,它会执行相同的操作:
由于 Laravel Collection items
存储为数组,因此不需要 toArray()
方法调用。
关于php - 将 Laravel 集合中的数组转换为 json 中包含数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36849481/