英文:
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
$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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论