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

如何通过点分隔的字符串键路径访问或操作PHP数组对应元素

实现方案

读取指定路径的数组值

先把点分隔的路径字符串拆成独立的键列表,再逐层遍历数组匹配键即可。

function getArrayValueByPath(array $arr, string $path)
{
    $keys = explode('.', $path);
    $current = $arr;
    foreach ($keys as $key) {
        // 数字键转int类型,避免字符串键和数字键匹配失败
        if (is_numeric($key)) {
            $key = (int)$key;
        }
        if (!isset($current[$key])) {
            return null; // 路径不存在时返回null,可按需改为抛出异常
        }
        $current = $current[$key];
    }
    return $current;
}

// 调用示例
$str = 'svg.1.linearGradient.0.@style';
$value = getArrayValueByPath($arr, $str);

删除指定路径的数组键

删除逻辑和读取基本一致,唯一区别是需要遍历到路径的倒数第二个键,拿到父级数组后再删除最后一级键,不能直接遍历到最后一级(最后一级拿到的是值,无法执行unset操作)。

function unsetArrayKeyByPath(array &$arr, string $path): bool
{
    $keys = explode('.', $path);
    $keyCount = count($keys);
    if ($keyCount === 0) {
        return false;
    }
    $current = &$arr;
    for ($i = 0; $i < $keyCount - 1; $i++) {
        $key = $keys[$i];
        if (is_numeric($key)) {
            $key = (int)$key;
        }
        if (!isset($current[$key]) || !is_array($current[$key])) {
            return false; // 路径不合法,删除失败
        }
        $current = &$current[$key];
    }
    $lastKey = $keys[$keyCount - 1];
    if (is_numeric($lastKey)) {
        $lastKey = (int)$lastKey;
    }
    if (isset($current[$lastKey])) {
        unset($current[$lastKey]);
        return true;
    }
    return false;
}

// 调用示例
$str = 'svg.1.linearGradient.0.@style';
unsetArrayKeyByPath($arr, $str);

注意:删除函数需要用引用传递数组和每一层的遍历结果,否则修改不会生效到原数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:06:03