phparrayslaravellaravel-collection

How to modify keys of nested array in Laravel?


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.


Solution

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