如何在Laravel中修改嵌套数组的键?

huangapple go评论67阅读模式
英文:

How to modify keys of nested array in Laravel?

问题

你可以尝试使用递归方法来处理嵌套数组,将所有键转换为蛇形命名法。以下是一种可能的方式:

function recursiveSnakeCaseKeys($array) {
    return collect($array)->map(function ($value, $key) {
        if (is_array($value)) {
            // 如果值是数组,递归处理它
            return recursiveSnakeCaseKeys($value);
        } else {
            // 否则,将键转换为蛇形命名法
            return [$key => $value];
        }
    })->flatMap(function ($item) {
        return $item;
    })->toArray();
}

$data = recursiveSnakeCaseKeys($array);

return $data;

这段代码将递归地处理嵌套数组,确保所有键都被转换为蛇形命名法。

英文:

I have an array that has some nested arrays, I would like to transform all the keys into snake case. I am trying this:

$data = collect($array)->keyBy(function ($value, $key) {
    return Str::snake($key);            
})->toArray();
        
return $data;

It is working fine, but only works for the parent array, nested arrays keep the same key:

[
    "some_key" => "value",
    "some_key" => [
        "someKey" => "value",
        "someKey" => [
            "someKey" => "value"
        ]
    ]
]

What can I do? thanks.

答案1

得分: 1

你可以使用辅助函数dotset来实现这个功能:

$flat = Arr::dot($array);
$newArray = [];
foreach ($flat as $key => $value) {
     // 这里可能只需使用Str::snake($key)。我没有检查过
    $newKey = collect(explode('.', $key))->map(fn ($part) => Str::snake($part))->join('.');
    Arr::set($newArray, $newKey, $value);
}
英文:

You can use the helpers dot and set for this:

$flat = Arr::dot($array);
$newArray = [];
foreach ($flat as $key => $value) {
     // You might be able to just use Str::snake($key) here. I haven't checked
    $newKey = collect(explode('.', $key))->map(fn ($part) => Str::snake($part))->join('.');
    Arr::set($newArray, $newKey, $value);
}

huangapple
  • 本文由 发表于 2023年6月6日 03:10:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定