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

从多维数组中提取同名数组

从多维数组中提取同名数组

PHP
冉冉说 2021-11-05 14:49:55
我有一个来自表示表单的 json 的数组。我必须将所有 [components] 收集到一个新数组中我解决了对 foreach 的认真处理,并在每个循环中使用了逻辑:如果不存在数组“组件”-> 检查是否是类型列如果是,检查是否存在“组件”并保存在新数组中如果不保存在新数组中如果再次存在,则对 3 或 4 个子级别应用与第 1 点相同的条件。这是我需要的最后一个数组Array        (            [0] => Array                (                    [key] => number1                    [type] => number                    [input] => 1                    [label] => Test Number Field                )            [1] => Array                (                    [key] => testRadioFiled                    [type] => radio                    [label] => Test Radio Filed                    [values] => Array                        (                            [0] => Array                                (                                    [label] => First                                    [value] => first                                    [shortcut] =>                                 )                        )                )            ......            [2] => Array                (                    [key] => testSelectMultipleField                    [data] => Array                        (                            [values] => Array                                (                                    [0] => Array                                        (                                            [label] => First                                            [value] => first                                        )                                    [1] => Array                                        (                                            [label] => Second                                            [value] => second                                        )
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

如果我理解你正确递归可以帮助:


function extractComponents($arrayWithComponents)

{

    $components = [];


    if (!isset($arrayWithComponents['components']) || !is_array($arrayWithComponents['components'])) {

        return $components;

    }


    foreach ($arrayWithComponents['components'] as $component) {

        if (isset($component['columns'])) {

            foreach ($component['columns'] as $column) {

                $components = array_merge($components, extractComponents($column));

            }

        } else {

            $components = array_merge($components, extractComponents($component));

            unset($component['components']);

            $components[] = $component;

        }

    }


    return $components;

}


var_dump(extractComponents($data));


查看完整回答
反对 回复 2021-11-05
  • 1 回答
  • 0 关注
  • 108 浏览

添加回答

举报

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