php - 通过点分隔键删除多维数组中的子树

标签 php arrays

我想通过点分隔键删除特定的子数组。这是一些有效的代码(是的,它有效,但还远未达到好的解决方案):

$Data = [
                'one',
                'two',
                'three' => [
                    'four' => [
                        'five' => 'six', // <- I want to remove this one
                        'seven' => [
                            'eight' => 'nine'
                        ]
                    ]
                ]
            ];

            # My key
            $key = 'three.four.five';
            $keys = explode('.', $key);
            $str = "";
            foreach ($keys as $k) {
                $sq = "'";
                if (is_numeric($k)) {
                    $sq = "";
                }
                $str .= "[" . $sq . $k . $sq . "]";
            }
            $cmd = "unset(\$Data{$str});";
            eval($cmd); // <- i'd like to get rid of this evil shit

对此有更好的解决方案吗?

最佳答案

您可以使用对数组内元素的引用,然后删除 $keys 数组的最后一个键。

您应该添加一些错误处理/检查键是否确实存在,但这是基础:

$Data = [ 
            'one',
            'two',
            'three' => [
                'four' => [
                    'five' => 'six', // <- I want to remove this one
                    'seven' => [
                        'eight' => 'nine'
                    ]
                ]
            ]
];

# My key
$key = 'three.four.five';
$keys = explode('.', $key);

$arr = &$Data;
while (count($keys)) {
    # Get a reference to the inner element
    $arr = &$arr[array_shift($keys)];

    # Remove the most inner key
    if (count($keys) === 1) {
        unset($arr[$keys[0]]);
        break;
    }
}

var_dump($Data);

A working example .

关于php - 通过点分隔键删除多维数组中的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46318228/

相关文章:

c - 为什么我的程序不能用于大型数组?

php - pdo - 在非对象上调用成员函数 prepare()

php - 循环遍历数组和 MySQL 查询每个元素 - Laravel

php - 运行第二个循环时取消设置数据

php - wp_redirect() 函数在 WP 管理中不起作用

php - 将 php 搜索数组与查询结果相结合 - 内连接 php 数组

c 字符串和文件操作

arrays - 保持点相关性,同时展平二维网格

php - 供应商文件夹应该在源代码管理中吗?

javascript - Ajax 从 mysql 查询填充表单