Convert Multidimensional PHP Arrays to 2D Arrays with Dot Notation Keys
Flattening multidimensional PHP arrays into 2D arrays with dot notation keys can be beneficial in various scenarios. It allows you to seamlessly access nested array values using dot notation, which enhances code readability and maintainability.
Recursive Function to Convert Nested Arrays
Fortunately, PHP provides a recursive function that can elegantly achieve this conversion:
$result = array();
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));
foreach ($ritit as $leafValue) {
$keys = array();
foreach (range(0, $ritit->getDepth()) as $depth) {
$keys[] = $ritit->getSubIterator($depth)->key();
}
$result[join('.', $keys)] = $leafValue;
}
Explanation:
Output:
This function will generate the desired 2D array with dot notation keys:
$newArray = array(
'key1' => 'value1',
'key2.subkey' => 'subkeyval',
'key3' => 'value3',
'key4.subkey4.subsubkey4' => 'subsubkeyval4',
'key4.subkey4.subsubkey5' => 'subsubkeyval5',
'key4.subkey5' => 'subkeyval5'
);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3