Last active
June 15, 2023 23:43
-
-
Save nhobi/5cadc0860025a4c4cccca9423167f11c to your computer and use it in GitHub Desktop.
Collection keyByRecursive macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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