1

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.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
DeveloperX
  • 517
  • 5
  • 23

1 Answers1

1

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);
}
apokryfos
  • 38,771
  • 9
  • 70
  • 114