将对象数组扁平化为指定值的数组

3

我正在使用Laravel 5.1获取一组相关问题的分类。

我只想要嵌套问题的ID,但为了让select起作用,我需要指定连接列,也就是category_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},
    ...
  ]
 }, ...
]

我该如何将questions : [中的内容仅限于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和list收集ID,但这样做不起作用:

我尝试使用map和list收集ID。这种方法行不通:

    $test = collect($categories)->map(function ($q) {
        return collect($q)->lists('id')->toArray();
    });

我希望在这里处理它,这样我就不需要在前端处理它。


考虑使用Presenter来DRY化您的代码。这是一个示例:https://github.com/thephpleague/fractal - Mysteryos
函数式实现:https://3v4l.org/5a0pA - mickmackusa
1个回答

2

这里有一个简单的方法来实现。

根据您的数据,这里提供一个示例数据,只需复制即可。

[
 {
  "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_encode($categories)将其转换为JSON格式。

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接