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

zour9fqk  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(217)

我有一个数组,其中有一些嵌套数组,我想把所有的键转换成蛇的情况。我正在尝试这个:

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

它工作正常,但只对父数组有效,嵌套数组保持相同的键:

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

我该怎么办?谢谢。

xuo3flqw

xuo3flqw1#

你可以使用助手dotset来实现:

$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);
}

相关问题