In this post I would like to share with you code snippet, which you can use to flatten nested array into one array with string keys with dot notation. This function takes nested array as input.
While working with laravel framework, I found array_flatten() method, this method will also flatten a multi-dimensional array into a single level array but only difference is , it does not support string indexes, it will return final array with numeric indexes.
The following is what I came up to flatten array with same keys and depth with dot notation. see the below example output for better understanding.
$value) { if(is_array($value)) { $result = $result + array_flatten($value, $prefix . $key . '.'); } else { $result[$prefix.$key] = $value; } } return $result; }
How to use
$data = array( 'user' => array( 'email' => '[email protected]', 'name' => 'arjun', 'account' => array( 'name' => 'Blogger', 'admin' => '[email protected]' ) ), 'post' => 'Hello, World!' ); print_r(array_flatten($data)); /* output : Array ( [user.email] => [email protected] [user.name] => arjun [user.account.name] => Blogger [user.account.admin] => [email protected] [post] => Hello, World! ) */