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

时间:2016-04-14 05:27:08

标签: php arrays laravel laravel-5

我使用Laravel 5.1获得了一组带有相关问题的类别。

我只想要嵌套问题的ID,但为了让Endpoint=sb://<your-servicebus-namespace>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<SAS-key-value>起作用,我需要指定连接列,即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}, ... ] }, ... ] 只包含ID而不是对象,所以它是:

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 ...
  ]
 }, ...
]

我更愿意在这里处理,所以我不需要在前端处理它。

1 个答案:

答案 0 :(得分:1)

这是一种简单的方法。

以下是根据您的数据进行复制的示例数据

[
 {
  "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 FORMAT

希望它有所帮助。