通过路径取消多维数组中的元素

时间:2018-02-22 15:32:45

标签: php arrays multidimensional-array

我试图删除多维数组中的元素。

需要删除的元素由globals.connects.setting1之类的字符串给出。这意味着我打算像这样修改一个数组:

// Old Array
$old = array(
    "globals" => array(
        "connects" => array(
            "setting1" => "some value",
            "setting2" => "some other value",
            "logging" => array()),
    "someOtherKey" => 1
));

// After modification
$new = array(
    "globals" => array(
        "connects" => array(
            "setting2" => "some other value",
            "logging" => array()),
    "someOtherKey" => 1
));

不幸的是,我不知道"深度"给定字符串的数量,也不是数组的确切结构。如果数组unsetElement($path, $array)$new作为参数给出,我正在寻找像$old这样的函数返回数组globals.connects.setting1

由于安全原因,我希望避免使用eval()功能。

1 个答案:

答案 0 :(得分:-1)

  $testArr = [
        "globals" => [
            "connects" => [
                'setting1' => [
                    'test' => 'testCon1',
                ],
                'setting2' => [
                    'abc' => 'testCon2',
                ],
            ],
        ],
        'someOtherKey' => [],
    ];

$pathToUnset = "globals.connects.setting2";

    function unsetByPath(&$array, $path) {
        $path = explode('.', $path);
        $temp = & $array;

        foreach($path as $key) {
            if(isset($temp[$key])){
                if(!($key == end($path))) $temp = &$temp[$key];
            } else {
               return false; //invalid path
            }
        }
        unset($temp[end($path)]);
    }

    unsetByPath($testArr, $pathToUnset);