为了账号安全,请及时绑定邮箱和手机立即绑定

如何取消设置嵌套 foreach 中的每个数组?

如何取消设置嵌套 foreach 中的每个数组?

PHP
达令说 2022-07-22 10:45:15
我有一个像这样的多维数组输出:    Array(    [0] => Array        (            [item] => null            [count] => 0            [child] => Array                (                    [Dagadu Bocah] => Array                        (                            [item] => Dagadu Bocah                            [count] => 47                            [child] => Array                                (                                    [HirukPikuk] => Array                                        (                                            [item] => HirukPikuk                                            [count] => 5                                            [child] => Array                                                (                                                    [DGD] => Array                                                        (                                                            [item] => DGD                                                            [count] => 1                                                            [child] =>                                                         )                                                )                                        )在我的期望中,我可以使用unsetforeach 循环中的函数来删除每个具有 3 个键的数组,即“item”、“count”和“child”,以便它生成一个如下所示的数组:      Array(    [0] => ([Dagadu Bocah] =>Array([HirukPikuk] =>Array([DGD])      }}谁能帮忙?
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

对于您想要使用recursion的那种数据,如下所示:


<?php

function getChildKey(array $data)

{

    $result = [];


    if (isset($data['child'])) {

        foreach ($data['child'] as $key => $value) {

            $result[$key] = getChildKey($value);

        }

    }


    if (empty($result)) {

        return '';

    }


    return $result;

}


$input = [

    [

        'item'  => null,

        'count' => 0,

        'child' => [

            'Dagadu Bocah' => [

                'item'  => 'Dagadu Bocah',

                'count' => 47,

                'child' => [

                    'HirukPikuk' => [

                        'item'  => 'HirukPikuk',

                        'count' => 5,

                        'child' => [

                            'DGD' => [

                                'item'  => 'DGD',

                                'count' => 1,

                                'child' => null,

                            ],

                        ],

                    ],

                ],

            ],

        ],

    ],

];


$output = [];

print_r($input);


foreach ($input as $index => $child) {

    $output[$index] = getChildKey($child);

}


print_r($output);


查看完整回答
反对 回复 2022-07-22
  • 1 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信