phparraysforeachappendarrayiterator

How do I append an element with a key using ArrayIterator in PHP?


There is no documentation on the PHP site for the ArrayIterator object beyond a basic parameter reference, so I'm not even sure this is possible.

I understand the concept of the ArrayIterator in a basic sense like this example:

$rows = new ArrayIterator(array('a', 'b', 'c'));
foreach ($rows as $row) {
    echo "<p>This is row {$a}.</p>";
}

In my case, the rows array is a little more complex (though still simplified for the sake of this example)...

$rows = array(
    'a' => NULL,
    'b' => array('d' => NULL, 'e' => NULL, 'f' => NULL),
    'c' => NULL
);
$rows = new ArrayIterator($rows);

The idea is that 'b' in this case, has a number of child elements that should be parsed as if they were parent elements, at the end (not necessary to process in order) of the rest of the parent elements (a,b,c).

Normally I would just use...

foreach ($child as $c) {
    $rows->append($c);
}

But in this case $child is an array with a key that I want to maintain...

foreach ($child as $key => $c) {
    $rows->append($c);  // but what about $key???
}

I don't want to add an array as an element on the end, I want to add the key and the value to the parent list so we would end up with....

$rows = array(
    'a' => ...,
    'b' => ...,
    'c' => ...,
    'd' => ...,
    'e' => ...,
    'f' => ...
);

Question: Is it possible to append an element to the currently iterating array from within a foreach loop with a key?


Solution

  • ArrayIterator implements ArrayAccess interface. That's mean that offsetset is available, and you can assign a value to the specified offset.

    As said the foreach documentation:

    In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

    But in this case isn't needed.

    $rows = array(
        'a' => 1,
        'b' => array('d' => 3, 'e' => 4, 'f' => 5),
        'c' => 2
    );
    
    $rows = new ArrayIterator($rows);
    
    foreach ($rows as $key => $row) {
        if (is_array($row)) { 
            foreach ($row as $key => $c) {
                $rows[$key] = $c;
            }
    
            // skip this
            continue;
        }
    
        echo $key, " ", $row, "\n";
    }
    

    This print:

    a 1
    c 2
    d 3
    e 4
    f 5
    

    Demo.