"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2025-01-15
Browse:690

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:

$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:

  • 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:

$newArray = array(
    'key1' => 'value1',
    'key2.subkey' => 'subkeyval',
    'key3' => 'value3',
    'key4.subkey4.subsubkey4' => 'subsubkeyval4',
    'key4.subkey4.subsubkey5' => 'subsubkeyval5',
    'key4.subkey5' => 'subkeyval5'
);
Latest tutorial More>

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