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

Mary-Kate Olsen
Release: 2024-10-28 00:24:29
Original
467 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!