php - 将对象数组展平为指定值的数组

标签 php arrays laravel laravel-5

<分区>

我正在使用 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 收集并列出 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_encode($categories) 为 JSON 格式

希望对您有所帮助。

关于php - 将对象数组展平为指定值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614495/

相关文章:

php - 如何以编程方式在 WordPress 中创建帖子

php - PHP 中带有 && 和多个 OR 条件的 if 语句

javascript - 将 json 对象数组转换为不同的格式

C程序: Integer array pointer changes values when passed as parameter

html - 如何将 html 元素从 Laravel Controller 传递给 View

php - Laravel 5.1 如何检查目录中是否存在文件?

php - 最后使用 laravel 订购空值

php - 使用 PHP 查找谁在托管网站

javascript - Action Script 3. 检查数组是否有元素不跳转,然后跳转

php - 将数据从另一个表获取到 Blade foreach - Laravel