首页 > 解决方案 > 如何根据列值中的数组更改集合

问题描述

我想更改 laravel 集合,因为我想通过这个集合来生成报告。如何根据列中的值更改集合。

以前的:

Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 23
[form_type] => radio
[details] => [{"id":55 title:"AA" name:"BB"}, {"id":56 title:"CC" name:"DD"}]
)
[1] => stdClass Object
(
[id] => 24
[form_type] => checkbox
[details] => [{"id":57 title:"PP" name:"QQ"}, {"id":58 title:"RR" name:"SS"}]
)
)
)

--details 列有对象数组,我希望它如下格式:

Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 23
[form_type] => radio
[title] => "AA"
[name] =>  "BB"     
)
[1] => stdClass Object
(
[id] => 23
[form_type] => radio
[title] => "CC"
[name] =>  "DD"     
)        
[2] => stdClass Object
(
[id] => 24
[form_type] => checkbox
[title] => "PP"
[name] =>  "QQ"
)
[4] => stdClass Object
(
[id] => 24
[form_type] => checkbox
[title] => "RR"
[name] =>  "SS"
)
)
)

标签: phplaravelloopslaravel-5

解决方案


唯一的方法是使用 Laravel 集合的每个方法。我希望数据采用以下格式,您将获得所需的输出。

$data = collect([
    (object)["id" => 23, "form_type" => "radio", "details" => [["id" => 55, 'title' => "AA", 'name' => "BB"], ["id" => 56, 'title' => "CC", 'name' => "DD"]]]
]);
$result = collect();
$data->each(function($d) use ($result) {
    $d = collect($d);
    unset($t['id']);
    $tmp = collect($d['details']);
    $tmp->each(function($t) use (&$d, $result) {
        $result->push($d->forget('details')->merge($t));
    });
});
echo "<pre>";
print_r($result);

推荐阅读