微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP - 成对嵌套的 foreach 循环

如何解决PHP - 成对嵌套的 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",[
            "key" => "3","item" => [
                "name" => "John"
            ]
        ],[
            "key" => "4","item" => [
                "name" => "John"
            ]
        ]
    ],];

解决方法

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

$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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。