集合按分组并连接特定列laravel

eagi6jfj  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(376)

我有以下回应:


# items: array:4 [▼

    0 => array:6 [▼
      "taskID" => "5"
      "title" => "Idea for the Project"
      "resource" => "Fac - Architect"
      "start" => "Wed Jul 31 08:00:00 EEST 2019"
      "finish" => "Wed Jul 31 17:00:00 EEST 2019"
      "predecessors" => "-"
    ]
    1 => array:6 [▼
      "taskID" => "5"
      "title" => "Idea for the Project"
      "resource" => "Fac - PM"
      "start" => "Wed Jul 31 08:00:00 EEST 2019"
      "finish" => "Wed Jul 31 17:00:00 EEST 2019"
      "predecessors" => "-"
    ]
    2 => array:6 [▼
      "taskID" => "5"
      "title" => "Idea for the Project"
      "resource" => "King"
      "start" => "Wed Jul 31 08:00:00 EEST 2019"
      "finish" => "Wed Jul 31 17:00:00 EEST 2019"
      "predecessors" => "-"
    ]
    3 => array:6 [▼
      "taskID" => "5"
      "title" => "Idea for the Project"
      "resource" => "Stakeholder"
      "start" => "Wed Jul 31 08:00:00 EEST 2019"
      "finish" => "Wed Jul 31 17:00:00 EEST 2019"
      "predecessors" => "-"
    ]
  ]

我想将这些数组分组到一个数组中,并将资源名称连接起来,如下所示:


# items: array:4 [▼

      "taskID" => "5"
      "title" => "Idea for the Project"
      "resource" => [
          "Fac - Architect",
          "Second Resource",
           ...
        ],
      "start" => "Wed Jul 31 08:00:00 EEST 2019"
      "finish" => "Wed Jul 31 17:00:00 EEST 2019"
      "predecessors" => "-"

  ]

有什么帮助吗?如果它可以通过使用集合或数组函数而不需要使用许多for循环的方式来实现,那就太好了。我用的是拉威尔8。

tjrkku2a

tjrkku2a1#

不是最好的解决方案,但你可以这样做

<?php

$items = collect(YOUR_RESPONSE);
$firstItem = $items->shift();
$firstItem['resource'] = [$firstItem['resource']];

$items->reduce(function ($carry, $item) {
    $carry['resource'][] = $item['resource'];
    return $carry;
}, $firstItem);

然后 $items->all() 会给你想要的。

相关问题