Php 将对象数组展平为指定值的数组
我使用Laravel 5.1获得了一组包含相关问题的类别 我只需要嵌套问题的id,但要使Php 将对象数组展平为指定值的数组,php,arrays,laravel,laravel-5,Php,Arrays,Laravel,Laravel 5,我使用Laravel 5.1获得了一组包含相关问题的类别 我只需要嵌套问题的id,但要使选择起作用,我需要指定联接列,即类别id: $categories = Category::with(['questions'=>function($query){ $query->select('id', 'category_id'); }])->get(); 这让我明白: [ { "id": 1, "category": "Anatomy",
选择
起作用,我需要指定联接列,即类别id
:
$categories = Category::with(['questions'=>function($query){
$query->select('id', 'category_id');
}])->get();
这让我明白:
[
{
"id": 1,
"category": "Anatomy",
"created_at": "2016-04-13 00:46:12",
"updated_at": "2016-04-13 00:46:12",
"questions":[
{"id": 1, "category_id": 1},
{"id": 2, "category_id": 1},
{"id": 3, "category_id": 1},
{"id": 4, "category_id": 1},
...
]
}, ...
]
我如何才能让问题:[
只包含ID而不是对象,所以应该是:
[
{
"id": 1,
"category": "Anatomy",
"created_at": "2016-04-13 00:46:12",
"updated_at": "2016-04-13 00:46:12",
"questions":[
1, 2, 3, 4 ...
]
}, ...
]
我已尝试使用map收集并列出ID。这不起作用:
$test = collect($categories)->map(function ($q) {
return collect($q)->lists('id')->toArray();
});
我更喜欢在这里处理这个问题,所以我不需要在前端处理它。这里有一个简单的方法 下面是一个根据您的数据复制的示例数据
[
{
"id": 1,
"category": "Anatomy",
"created_at": "2016-04-13 00:46:12",
"updated_at": "2016-04-13 00:46:12",
"questions":[
{"id": 1, "category_id": 1},
{"id": 2, "category_id": 1},
{"id": 3, "category_id": 1},
{"id": 4, "category_id": 1}
]
}
]
下面是PHP代码
# JSON DATA
$data = '[
{
"id": 1,
"category": "Anatomy",
"created_at": "2016-04-13 00:46:12",
"updated_at": "2016-04-13 00:46:12",
"questions":[
{"id": 1, "category_id": 1},
{"id": 2, "category_id": 1},
{"id": 3, "category_id": 1},
{"id": 4, "category_id": 1}
]
}
]';
# convert to array
# $data = json data
$categories = json_decode($data, true);
# assuming the categories has a list of object
# so i need to override it all
foreach ($categories as $key => $category) {
# map a new array
$list = array_map(function ($data) {
return $data['id'];
}, $category['questions']);
# assign it to the current object being
# iterated the new array created from
# the array_map
$categories[$key]['questions'] = $list;
}
输出将如下所示
[
{
"id": 1,
"category": "Anatomy",
"created_at": "2016-04-13 00:46:12",
"updated_at": "2016-04-13 00:46:12",
"questions": [
1,
2,
3,
4
]
}
]
如果您使用json\u encode($categories)将使用json格式
希望能有所帮助。考虑使用演示者来擦干代码。这里有一个: