1

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

它看起来像这样:

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] => 88 下方 id 为 108 的数组。问题是将数组移动到新位置但同时移动子数组。

4

1 回答 1

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);
于 2012-10-18T09:51:19.200 回答