Home > Blockchain >  PHP how to use recursive array iterator
PHP how to use recursive array iterator

Time:08-18

I have a nested array like:

$array = [
   'fookey' => [
    [1, 2, 3],
    [10, 20, 30],
    ],
    'barkey' => [
    [a, b, c],
    [d, e, f],
    ]
]

I need to get 'fookey' and 'barkey' as a strings and every child arrays first and second value.

Count of child array may differ, but always have 3 elements.

I'm trying to iterate over that array using RecursiveArrayIterator:

$rii = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

foreach ($rii as $key => $val) {

    var_dump($val);

}

But i'm getting values 12 times and their indexes instead of 4 child arrays and 'fookey' or 'barkey'. I would appreciate your help!

CodePudding user response:

Not exactly sure what you need, but that is how I interpreted your question.

foreach ($array as $key => $value) {
    echo $key;
    echo $value[0] . ' - ' . $value[1];
}

CodePudding user response:

This will iterate and keep the first two elements of each child and merge them together.

foreach($array as &$value) {
    $value = array_merge(...array_map(fn($arr) => array_slice($arr, 0, 2), $value));
}

results in

Array
(
    [fookey] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 10
            [3] => 20
        )

    [barkey] => Array
        (
            [0] => a
            [1] => b
            [2] => d
            [3] => e
        )

)
  •  Tags:  
  • php
  • Related