PHP - 成对嵌套的 foreach 循环

时间:2021-01-04 10:19:21

标签: php laravel foreach

我正在尝试遍历一组 block 组件,每个组件可以有 n 个嵌套组件(profileavatar)。

现在,我想要做的是显示这些块 x 次,其中 x 是来自有效负载数组的数据数:

$payload['users'] = [
    ['name' => 'Oliver'],
    ['name' => 'John']
];

因此,由于上述有效负载 users 长度为 2,因此应呈现:

- block #1
  -- profile
  -- avatar
- block #2
  -- profile
  -- avatar

我试图通过使用嵌套的 foreach 循环以相同的方式呈现上述内容。看下面的代码:

$payload['users'] = [
    ['name' => 'Oliver'],
    ['name' => 'John']
];

$schema = [
    "id" => 1,
    "name" => "Users",
    "components" => [
        [
            "key" => "0",
            "name" => "block",
            "components" => [
                [
                    "key" => "1",
                    "name" => "profile"
                ],
                [
                    "key" => "2",
                    "name" => "avatar"
                ]
            ],
        ]
    ],
];

$toPush = [];
foreach ($schema['components'] as $key => $value) {
    
        foreach ($value['components'] as $no => $component) {
                $iterator = $payload['users'];
                for ($x = 0; $x < count($iterator); $x ++) {
                    $copy = $component;
                    $copy['item'] = $iterator[$x];
                    $copy['key'] = $copy['key'] . '-' . $x;
                    $toPush[] = $copy;
                }
            $schema['components'][$key]['components'] = $toPush;
        }
}

print_r($toPush);

问题是上面打印出来是这样的:

- block #1
  -- profile
  -- profile
- block #2
  -- avatar
  -- avatar

我为此创建了一个 3v4l,可以在 here 中找到。

如何实现我想要的场景?

作为参考,我使用的是 Laravel 框架。

期望的输出

也可用作 3v4l here

[
    "components" => [
        [
            "key" => "1",
            "name" => "profile",
            "item" => [
                "name" => "Oliver"
            ]
        ],
        [
            "key" => "2",
            "name" => "avatar",
            "item" => [
                "name" => "Oliver"
            ]
        ],
        [
            "key" => "3",
            "name" => "profile",
            "item" => [
                "name" => "John"
            ]
        ],
        [
            "key" => "4",
            "name" => "avatar",
            "item" => [
                "name" => "John"
            ]
        ]
    ],
];

1 个答案:

答案 0 :(得分:1)

这个逻辑可能对你有帮助。

$toPush = [];
$count = 0;
foreach ($schema['components'] as $value) {
    foreach ($value['components'] as $key => $component) {
        foreach ($payload['users'] as $idx => $user) {
            $toPush['components'][$count]['key'] = $count;
            $toPush['components'][$count]['name'] = $value['components'][$idx]['name'];
            $toPush['components'][$count]['item'] = $payload['users'][$key];
            $count++;
        }
    }
}

demo