Skip to content

Instantly share code, notes, and snippets.

@nhobi
Last active June 15, 2023 23:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nhobi/5cadc0860025a4c4cccca9423167f11c to your computer and use it in GitHub Desktop.
Save nhobi/5cadc0860025a4c4cccca9423167f11c to your computer and use it in GitHub Desktop.
Collection keyByRecursive macro
<?php
Illuminate\Support\Collection::macro('keyByRecursive', function ($func) {
return $this->keyBy(function ($value, $key) use ($func) {
return $func($value, $key);
})->map(function ($item) use ($func) {
if ($item instanceof Illuminate\Support\Collection) {
return $item->keyByRecursive($func);
}
if (is_array($item) || is_object($item)) {
return collect($item)->keyByRecursive($func);
}
return $item;
});
});
<?php
$collection = collect([
[
'key_one' => [
'sub_key_one' => collect([
'sub_sub_key_one' => 'final value one',
'sub_sub_key_two' => 2,
'sub_sub_key_three' => 3.0,
]),
'sub_key_two' => (object) [
'sub_sub_key_one' => 'final value one',
'sub_sub_key_two' => 2,
'sub_sub_key_three' => 3.0,
],
'sub_key_three' => [
'sub_sub_key_one' => 'final value one',
'sub_sub_key_two' => 2,
'sub_sub_key_three' => 3.0,
],
],
],
]);
$result1 = $collection->keyByRecursive(function ($value, $key) {
return camel_case($key);
})->toArray();
array_walk_recursive($result1, function ($item, $key) {
$this->assertTrue(camel_case($key) === $key);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment