Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中从下至上删除递归数组中的元素_Php_Arrays_Recursion - Fatal编程技术网

在PHP中从下至上删除递归数组中的元素

在PHP中从下至上删除递归数组中的元素,php,arrays,recursion,Php,Arrays,Recursion,给定以下数组: array( 0 => array( 0 => 56, 1 => array( 0 => 57, 1 => 58, 2 => 59, ), 2 => 60 ), 1 => array( 0 => 61, 1 => array(

给定以下数组:

array(
    0 => array(
        0 => 56,
        1 => array(
            0 => 57,
            1 => 58,
            2 => 59,
        ),
        2 => 60
    ),
    1 => array(
        0 => 61,
        1 => array(
            0 => 62,
            1 => array(
                0 => 63,
                1 => 64
            )
        )
    )
)
$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($ids),
    RecursiveIteratorIterator::LEAVES_ONLY
);

$ids = [];

foreach ($iterator as $id) {
    // You can put elements directly in the beggining of an array
    // or reverse array later.
    // array_unshift($ids, $id);
    $ids[] = $id;
}

$ids = array_reverse($ids);
如何从最深的元素开始从该数组中删除元素?我的元素是数据库中的ID,关键约束使我无法删除有子元素的父元素

我在寻找一些有用的东西,但到目前为止还没有解决方案


编辑
实际上,不需要获得特定的算法,标准递归将完成此任务

您可以使用和
递归迭代器::leaves_only
模式访问leaves only,然后反转生成的数组:

array(
    0 => array(
        0 => 56,
        1 => array(
            0 => 57,
            1 => 58,
            2 => 59,
        ),
        2 => 60
    ),
    1 => array(
        0 => 61,
        1 => array(
            0 => 62,
            1 => array(
                0 => 63,
                1 => 64
            )
        )
    )
)
$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($ids),
    RecursiveIteratorIterator::LEAVES_ONLY
);

$ids = [];

foreach ($iterator as $id) {
    // You can put elements directly in the beggining of an array
    // or reverse array later.
    // array_unshift($ids, $id);
    $ids[] = $id;
}

$ids = array_reverse($ids);

以下是。

您需要从最深的元素遍历数组到父元素,以从数据库中删除记录。是吗?是的,但我可以从父母到孩子做到这一点:如果我的父母有孩子,请检查孩子并删除。然后重新检查它是否还有孩子。如果没有,请删除它并继续,然后再解释一点。你需要56,57,58形式的ID…?我需要先删除57,58,59,然后是56,然后是60,然后是63,64,然后是62,然后是61,就是这样!伟大的非常感谢。