php将节点移动到父数组

时间:2010-09-12 07:55:50

标签: php arrays

如何将'fields'数组的所有节点移动到其父数组'113'中,同时取消设置'fields'?

    [a] => Array
    (
        [113] => Array
            (
                [title] => asdfasdfas
                [alias] => asdfasdfas
                [fields] => Array
                    (
                        [jr_streetaddress] => Array
                            (
                                [type] => text
                                [label] => Street Address
                                [data] => asdfasdffsd
                            )

                        [jr_towncity] => Array
                            (
                                [type] => text
                                [label] => Town / City
                                [data] => Nottingham
                            )
                    )
            )
     )

2 个答案:

答案 0 :(得分:3)

假设您的顶级数组($something['a'])是变量$a

foreach($a as $key => $values){
  if(isset($values['fields']))
    {
       $a[$key] = array_merge($a[$key], (array) $values['fields']);
       unset($a[$key]['fields']);
    }
}

或者,如果你不想点击$a中的每个数组元素,你可以删除循环并用$values$a[113]替换$key 113 }。

还要注意将fields元素转换为数组jsut,以防它不是(array) $values['fields']

答案 1 :(得分:0)

如果你可以像这样制作这个数组:

[a] => Array
(
    [113] => Array
        (
            [title] => asdfasdfas
            [alias] => asdfasdfas
            [jr_streetaddress] => Array
                        (
                            [type] => text
                            [label] => Street Address
                            [data] => asdfasdffsd
                        )

            [jr_towncity] => Array
                        (
                            [type] => text
                            [label] => Town / City
                            [data] => Nottingham
                        )
        )
 )

尝试使用此代码:

$array['a'][113]['jr_streetaddress'] = $array['a'][113]['fields']['jr_streetaddress'];
$array['a'][113]['jr_towncity'] = $array['a'][113]['fields']['jr_towncity'];
unset($array['a'][113]['fields']);