【问题标题】:How to transform a Laravel collection by keys?如何按键转换 Laravel 集合?
【发布时间】:2020-01-06 00:42:35
【问题描述】:

我有一个 Laravel 集合,其中有用户数据(他们的帖子、cmets 和声誉)。我想转换这个集合,其中每个项目都成为三个属性之一(帖子、cmets 和声誉)。

所以结果会像 - 对于字段:'posts' 和 user_id: 46,我们有 1542 个帖子。对于字段:'cmets',同一用户有 2 个。等

我尝试在集合上创建多个循环以获得此结果,但它不起作用,因为我不知道我需要多少循环。有没有更好更干净的方法来做到这一点?

这是我的原始收藏

"data": [
    {
        "user_id": 46,
        "username": "johnive",
        "posts": 1542,
        "comments": 2,
        "reputation": 48.5,
    },

    {
        "user_id": 30,
        "username": "zacky13",
        "posts": 54,
        "comments": 16,
        "reputation": 14.3,
    },

    {
        "user_id": 107,
        "username": "lil_elf4",
        "posts": 564,
        "comments": 60,
        "reputation": 67.5,
    },
],

这是我想要达到的结果

"data": [
    {
        "user_id": 46,
        "username": "johnive",
        "field": "posts",
        "value": 1542
    },

    {
        "user_id": 46,
        "username": "johnive",
        "field": "comments",
        "value": 2
    },

    {
        "user_id": 46,
        "username": "johnive",
        "field": "reputation",
        "value": 48.5
    },

    {
        "user_id": 30,
        "username": "zacky13",
        "field": "posts",
        "value": 54
    },

    {
        "user_id": 30,
        "username": "zacky13",
        "field": "comments",
        "value": 16
    },

    ...
],

我尝试使用多个循环似乎是一种肮脏的方式,我不知道我需要多少个循环。

foreach ($collection as $item)
{
  $new_item = new stdClass;

  $new_item->user_id = $item->user_id;
  $new_item->username = $item->username;
  $new_item->field = 'posts';
  $new_item->value = $item->posts;
}

foreach ($collection as $item)
{
  $new_item = new stdClass;

  $new_item->user_id = $item->user_id;
  $new_item->username = $item->username;
  $new_item->field = 'comments';
  $new_item->value = $item->comments;
}

foreach ($collection as $item)
{
  $new_item = new stdClass;

  $new_item->user_id = $item->user_id;
  $new_item->username = $item->username;
  $new_item->field = 'reputation';
  $new_item->value = $item->reputation;
}

【问题讨论】:

    标签: php arrays laravel collections


    【解决方案1】:

    你可以做到,例如像这样:

    $result = collect();
    foreach ($collection as $item)
    {
      foreach(['posts', 'comments', 'reputations'] as $type) {
        $new_item = new stdClass;
        $new_item->user_id = $item->user_id;
        $new_item->username = $item->username;
        $new_item->field = $type;
        $new_item->value = $item->$type;
        $result->push($new_item);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2018-02-26
      • 2018-08-01
      • 2018-12-31
      相关资源
      最近更新 更多