/**
     * unset多维数组中指定的key
     * @param $arr
     * @param $name "a[b]" or "1[1]"
     * @return bool
     */
    public static function unsetByIndex(&$array, $name)
    {
        $matches = [];
        if(!preg_match_all('/\[?([\w-]+)\]?/', $name, $matches)) {
            return false;
        }
        if(!empty($matches) && !empty($matches[1])) {
            $indexToRemove = $matches[1];
            $lastIndex = array_pop($indexToRemove);
            foreach ($indexToRemove as $index) {
                if (isset($array[$index]) && is_array($array[$index])) {
                    $array = &$array[$index];
                } else {
                    // Element or index doesn't exist
                    return false;
                }
            }
            if (isset($array[$lastIndex])) {
                unset($array[$lastIndex]);
                return true;
            }
        }
        return false;
    }
测试demo
$multiArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

unsetByIndex($multiArray, '1[1]');
print_r($multiArray);
//结果
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )

)

标签: none

添加新评论