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

Laravel中如何将嵌套数组的所有键转换为蛇形命名?

解决嵌套数组所有键转为蛇形命名的问题

你当前的代码只处理了数组的顶层键,因为keyBy方法仅作用于集合的第一层元素,不会递归遍历嵌套的数组结构。要实现所有层级的键转为蛇形命名,需要编写一个递归函数来处理每一层的数组。

递归实现方案

use Illuminate\Support\Str;

function convertKeysToSnakeCase(array $array): array
{
    $converted = [];

    foreach ($array as $key => $value) {
        // 将当前键转为蛇形命名
        $snakeKey = Str::snake($key);

        // 如果值是数组,递归处理嵌套结构
        if (is_array($value)) {
            $converted[$snakeKey] = convertKeysToSnakeCase($value);
        } else {
            $converted[$snakeKey] = $value;
        }
    }

    return $converted;
}

使用方式

直接传入你的原始数组即可完成全层级转换:

$originalArray = [
    "someKey" => "value",
    "anotherKey" => [
        "someNestedKey" => "value",
        "deepNestedKey" => [
            "finalKey" => "value"
        ]
    ]
];

$convertedArray = convertKeysToSnakeCase($originalArray);

转换后的结果会是:

[
    "some_key" => "value",
    "another_key" => [
        "some_nested_key" => "value",
        "deep_nested_key" => [
            "final_key" => "value"
        ]
    ]
]

为什么原来的代码不生效?

collect($array)->keyBy(...)只会修改集合顶层元素的键,不会遍历处理嵌套的子数组。递归函数则会遍历每一个键值对,遇到数组类型的值就继续深入处理,确保所有层级的键都被转换为蛇形命名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:27:08