How to modify keys of nested array in laravel?

by darrion.kuhn , in category: PHP Frameworks , 2 months ago

How to modify keys of nested array in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 2 months ago

@darrion.kuhn 

To modify keys of nested arrays in Laravel, you can use the map function in combination with the array_dot and array_change_key_case functions. Here is an example of how you can modify keys of nested arrays:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$array = [
    'foo_bar' => [
        'baz_qux' => 'value',
    ],
];

$modifiedArray = collect($array)->map(function ($item, $key) {
    return is_array($item) ? 
        array_change_key_case(array_dot($item), CASE_UPPER) : 
        $item;
})->all();

print_r($modifiedArray);


In this example, the array is transformed into a collection, and then the map function is used to loop through each item in the array. If the item is an array, we use the array_dot function to flatten the array and then the array_change_key_case function to change the keys to uppercase. Finally, we convert the collection back to an array using the all() method and print the modified array using the print_r function.


This is just one way to modify keys of nested arrays in Laravel. There are other approaches depending on the specific requirements of your project.