How to parse nested array with laravel?

by giovanny.lueilwitz , in category: PHP Frameworks , 5 months ago

How to parse nested array with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 5 months ago

@giovanny.lueilwitz 

To parse a nested array in Laravel, you can use the array_dot function to flatten the nested array into a single level array. Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$data = [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'address' => [
        'street' => '123 Main St',
        'city' => 'New York',
        'zip' => '10001'
    ]
];

$flattenedData = array_dot($data);

// Output the flattened array
dd($flattenedData);


This will output:

1
2
3
4
5
6
7
[
    'name' => 'John Doe',
    'email' => '[email protected]',
    'address.street' => '123 Main St',
    'address.city' => 'New York',
    'address.zip' => '10001'
]


You can now access the nested array values using the dot notation, for example:

1
2
// Accessing the street value
$street = $flattenedData['address.street'];


This way, you can easily parse and work with nested arrays in Laravel.