You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何扩展实现任意维度多维数组移除指定维度的通用函数

通用多维数组指定维度移除实现

原硬编码实现仅支持4维数组固定第3维的场景,通过递归遍历+动态路径访问的方式,可以扩展为支持任意维度、任意指定移除维度的通用函数,同时兼容两种调用形式。

核心实现思路

  • 兼容两种调用方式:传入3个参数时自动递归计算数组总维度,传入4个参数时直接使用手动传入的总维度做校验
  • 维度序号从1开始计数,和原代码中$i1/$i2/$i3/$i4的计数规则保持一致,避免维度序号混淆
  • 不硬编码嵌套循环层数,通过递归遍历适配任意维度的数组,移除指定维度时直接将该维度的索引固定为传入值,不将该层维度写入结果数组结构,自然实现降维

完整代码

<?php
function array_remove($a, $n, $ik, $ik0 = null) {
    // 适配3参数调用:array_remove($a, $ik, $ik0),自动计算数组总维度
    if (is_null($ik0)) {
        $ik0 = $ik;
        $ik = $n;
        // 递归探测数组总维度
        $n = 1;
        $temp = current($a);
        while (is_array($temp)) {
            $n++;
            $temp = current($temp);
        }
    }

    // 基础参数校验
    if ($ik < 1 || $ik > $n) {
        throw new InvalidArgumentException("待移除维度序号超出数组实际维度范围");
    }
    if (!is_array($a)) {
        throw new InvalidArgumentException("待处理内容不是合法数组");
    }

    // 递归构建降维后的数组
    $build = function($currentDim, $path) use ($a, $n, $ik, $ik0, &$build) {
        // 遍历到最深层时,按路径取出原始值
        if ($currentDim > $n) {
            $target = $a;
            foreach ($path as $idx) {
                $target = $target[$idx];
            }
            return $target;
        }
        // 当前维度是待移除维度,直接固定索引,不加入结果结构
        if ($currentDim == $ik) {
            $path[] = $ik0;
            return $build($currentDim + 1, $path);
        }
        // 普通维度:遍历所有连续整数键,递归构建子数组
        $curLevel = $a;
        foreach ($path as $p) {
            $curLevel = $curLevel[$p];
        }
        $levelLen = count($curLevel);
        $res = [];
        for ($i = 0; $i < $levelLen; $i++) {
            $newPath = $path;
            $newPath[] = $i;
            $res[$i] = $build($currentDim + 1, $newPath);
        }
        return $res;
    };

    return $build(1, []);
}

使用示例

  • 原4维数组固定第3维索引为$i30的场景,和原函数调用效果完全一致:
    // 自动识别维度写法
    $res = array_remove($arr4d, 3, $i30);
    // 手动指定总维度写法
    $res = array_remove($arr4d, 4, 3, $i30);
    
  • 其他场景调用参考:
    • 3维数组移除第2维,固定索引为2:$res = array_remove($arr3d, 2, 2);
    • 6维数组移除第5维,固定索引为0,手动指定总维度:$res = array_remove($arr6d, 6, 5, 0);

说明:当前实现默认适配从0开始的连续整数键数组,和原代码适配场景一致。如果需要支持非连续整数键、字符串键的数组,只需要把代码中遍历层级的for循环替换为foreach遍历即可。

内容的提问来源于stack exchange,提问作者Brethlosze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 01:45:43