移动多维数组中的元素。

时间:2012-10-18 09:38:44

标签: php arrays multidimensional-array

我有一个包含父项和子项的多维数组,我想更改数组键

看起来像这样:

Array
(
    [0] => stdClass Object
    (
        [id] => 108
        [parent_id] => 0
        [children] => Array
        (
            [0] => stdClass Object
            (
                 [id] => 71
                 [parent_id] => 108
                 [children] => Array
                 (
                     [0] => stdClass Object
                     (
                         [id] => 107
                         [parent_id] => 71
                         [children] => Array
                         (
                             [0] => stdClass Object
                             (
                                 [id] => 78
                                 [parent_id] => 107
                             )
                         )
                    )
                )
            )
        )
    )

    [1] => stdClass Object
    (
        [id] => 82
        [parent_id] => 0
    )

    [2] => stdClass Object
    (
        [id] => 84
        [parent_id] => 0
    )

    [3] => stdClass Object
    (
        [id] => 88
        [parent_id] => 0
    )

    [4] => stdClass Object
    (
        [id] => 92
        [parent_id] => 0
    )
)

我想移动,例如,数组[id] =>下面的id为108的数组88.问题是将一个数组移动到一个新位置,但同时移动子数组。

1 个答案:

答案 0 :(得分:0)

function array_remove($array, $index) {
    array_splice($array, $index, 1, array());
    return $array;
}

function array_insert($array, $element, $index) {
    array_splice($array, $index, 0, array($element));
    return $array;
}

function array_move($array, $from, $to) {
    $element = $array[$from];
    $array = array_remove($array, $from);
    $array = array_insert($array, $element, $to - 1);
    return $array;
}

$array = array_move($array, 0, 4);
print_r($array);