从PHP的底部到顶部从递归数组中删除元素 [英] Remove elements from recursive array from bottom to top in PHP

查看:73
本文介绍了从PHP的底部到顶部从递归数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数组:

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
            )
        )
    )
)

如何从最深的元素开始从该数组中删除元素?我的元素是数据库中的ID,关键限制使我无法删除有孩子的父母...

How could I proceed to remove elements from that array starting from deepest elements? My elements are ID in a database and key constraints make me unable to delete parents if they have children...

我使用 RecursiveIterator ,但到目前为止没有解决方法...

I looked for something using RecursiveIterator but no solution so far...

实际上,不需要获取特定的算法,标准的递归就可以完成

Actually, no need to get a specific algo, a standard recursion will do the job

推荐答案

您只能使用 RecursiveIteratorIterator RecursiveIteratorIterator :: LEAVES_ONLY 模式,然后反转结果数组:

You can visit leaves only with RecursiveIteratorIterator and RecursiveIteratorIterator::LEAVES_ONLY mode and then reverse the resulting array:

$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);

这里是工作演示

这篇关于从PHP的底部到顶部从递归数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆