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:
<code class="php">$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; }</code>
Explanation:
Output:
This function will generate the desired 2D array with dot notation keys:
<code class="php">$newArray = array( 'key1' => 'value1', 'key2.subkey' => 'subkeyval', 'key3' => 'value3', 'key4.subkey4.subsubkey4' => 'subsubkeyval4', 'key4.subkey4.subsubkey5' => 'subsubkeyval5', 'key4.subkey5' => 'subkeyval5' );</code>
The above is the detailed content of How to Convert Multidimensional PHP Arrays to 2D Arrays with Dot Notation Keys?. For more information, please follow other related articles on the PHP Chinese website!