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

如何将点分隔文本转换为对应键的嵌套多维数组?

点分隔字符串转PHP多维数组结构实现方案

核心实现思路:先通过.分割字符串得到层级键名数组,再遍历键名逐层拼接/操作数组即可。

场景1:生成$output['config']['google']['api']['key']格式的引用字符串

直接遍历分割后的键名拼接即可:

// 输入字符串
$dotPath = "config.google.api.key";
// 按点分割为层级数组
$keySegments = explode('.', $dotPath);
// 拼接目标字符串
$result = '$output';
foreach ($keySegments as $key) {
    $result .= "['{$key}']";
}

// 输出结果:$output['config']['google']['api']['key']
echo $result;

注意:如果你的键名本身包含单引号,拼接字符串时需要对键名做转义处理,将$result .= "['{$key}']";替换为$result .= "['" . addslashes($key) . "']";即可。

场景2:实际操作多维数组(读取/赋值)

实际开发中更常用的是直接根据点路径操作数组的取值和赋值,对应实现函数如下:

读取多维数组值

function getArrayValueByDotPath(array $targetArray, string $dotPath, $defaultValue = null)
{
    $keySegments = explode('.', $dotPath);
    foreach ($keySegments as $key) {
        if (!is_array($targetArray) || !array_key_exists($key, $targetArray)) {
            return $defaultValue;
        }
        $targetArray = $targetArray[$key];
    }
    return $targetArray;
}

// 调用示例
$testArray = [
    'config' => [
        'google' => [
            'api' => [
                'key' => 'test_key_123'
            ]
        ]
    ]
];
echo getArrayValueByDotPath($testArray, 'config.google.api.key'); // 输出 test_key_123

给多维数组指定路径赋值

function setArrayValueByDotPath(array &$targetArray, string $dotPath, $value): void
{
    $keySegments = explode('.', $dotPath);
    $current = &$targetArray;
    foreach ($keySegments as $key) {
        if (!isset($current[$key]) || !is_array($current[$key])) {
            $current[$key] = [];
        }
        $current = &$current[$key];
    }
    $current = $value;
}

// 调用示例
$output = [];
setArrayValueByDotPath($output, 'config.google.api.key', 'test_key_456');
// 此时 $output['config']['google']['api']['key'] 的值为 test_key_456

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:24:04