📜 ⬆️ ⬇️

Recursive array traversal

I came across an interesting post on the Internet, describing the use of SPL
The text is small, but I really liked the implementation.
Further translation (if you can call it that) + some ad-libbing

When a multilevel array appears in our program, in order to process it efficiently, you need to write a bunch of recursive functions or write a huge number of foreach, while or for cycles (like someone used to)

The simplest method for obtaining pairs (key, value) for such arrays is to use the capabilities of the SPL library, namely, the RecursiveArrayIterator and RecursiveIteratorIterator iterators

$ array_multi = array (
"MyKey" => "myValue",
"MyKey2" => array (
"MyKey2Array" => "value2Array",
"MyKey3Array" => "value3Array",
"MyKey4Array" => "value4Array",
“MyKey5Array” => array (“test”, “tata”, “france”)));
$ array_iterator = new RecursiveIteratorIterator (
new RecursiveArrayIterator ($ array_multi));
foreach ($ array_iterator as $ key => $ value)
echo $ key. ' - '. $ Value. "\ N";

')
The output of this short example is as follows:
myKey - myValue
myKey2Array - value2Array
myKey3Array - value3Array
myKey4Array - value4Array
0 - test
1 - tata
2 - france

Source: https://habr.com/ru/post/31422/


All Articles