0

我想递归更新下面的数组,用一些其他值替换包含 [myKey] 键的数组的内容(比如说 [foo] => bar,[bar] => foo)。这没有使用引用,因为我已经有一些代码在工作,但我想重构它。

Array
(
    [objects] => Array
        (
            [0] => Array
                (
                    [somekey] => value
                    [items] => Array
                        (
                            [0] => Array
                                (
                                    [myKey] => item1
                                )

                            [1] => Array
                                (
                                    [myKey] => item2
                                )
                        )
                )

            [1] => Array
                (
                    [otherKey] => other value
                    [items] => Array
                        (
                            [0] => Array
                                (
                                    [myKey] => item3
                                )

                            [1] => Array
                                (
                                    [myKey] => item4
                                )
                        )
                )

            [2] => Array
                (
                    [myKey] => item5
                )
        )
)

我最后想要的如下。不要考虑我将如何决定使用哪些键/值,而只是考虑如何将它们添加到数组中......

Array
(
    [objects] => Array
        (
            [0] => Array
                (
                    [somekey] => value
                    [items] => Array
                        (
                            [0] => Array
                                (
                                    [foo] => bar
                                )

                            [1] => Array
                                (
                                    [bar] => foo
                                )
                        )
                )

            [1] => Array
                (
                    [otherKey] => other value
                    [items] => Array
                        (
                            [0] => Array
                                (
                                    [whatever] => value
                                )

                            [1] => Array
                                (
                                    [foo1] => bar
                                )
                        )
                )

            [2] => Array
                (
                    [bar1] => foo2
                )
        )
)

提前致谢!

4

1 回答 1

3

你可以试试这个功能:

function replace_recursive_array($array, $old_key, $new_key, $new_value) {

    foreach ($array as $key => $value) {

        if (is_array($value)) {

            $array[$key] = replace_recursive_array($value, $old_key, $new_key, $new_value);

        }elseif($key == $old_key) {

            $array[$new_key] = $new_value;

        }

    }

    unset($array[$old_key]);          
    return $array;   

}
于 2013-07-15T13:10:47.990 回答