Home  >  Article  >  Backend Development  >  How to Convert Multidimensional PHP Arrays to 2D Arrays with Dot Notation Keys?

How to Convert Multidimensional PHP Arrays to 2D Arrays with Dot Notation Keys?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 00:24:29548browse

How to Convert Multidimensional PHP Arrays to 2D Arrays with Dot Notation Keys?

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:

  • The RecursiveIteratorIterator and RecursiveArrayIterator classes are used to iterate through the nested array recursively.
  • During each iteration, the key method of the RecursiveArrayIterator is used to capture the current key of the array.
  • The getSubIterator($depth) method is used to retrieve the sub-iterator at a specific depth, allowing us to iterate through nested arrays.
  • The range(0, $ritit->getDepth()) function creates an array of depths, traversing from the innermost array to the outermost array.
  • The join('.', $keys) function concatenates the array keys with a dot(.) as a separator, creating the dot notation key.
  • The resulting key-value pair is stored in the $result array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn