Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach() with arrays within arrays?

I want to call a function on each element in an array. This is obviously very easy with a foreach(), but where I start breaking down is when arrays contain arrays. Can someone help me out with a function that will execute some code for every key -> value pair from a set of arrays within arrays. The depth could, in theory, be infinite, but a good limit would be 3 iterations (array in array in array) if recursion couldn't work.

An example array would be one taken from $_POST below:

Array
(
    [languages] => Array
    (
        [0] => php
        [1] => mysql
        [2] => inglip
    )

    [rates] => Array
    (
        [incall] => Array
        (
            [1hr] => 10
        )

        [outcall] => Array
        (
            [1hr] => 10
        )

    )
)

Just to make sure, what I want to do is run a piece of code (a function) that is passed every 'end node' in the array structure, so in the example above, it would be called when...

[0] => php
[1] => mysql
[2] => inglip
[1hr] => 10
[1hr] => 10

... is found.

Thanks for any help,

James

like image 361
Bojangles Avatar asked Apr 02 '11 16:04

Bojangles


2 Answers

That's a perfect job for Iterators:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
    echo "$key => $value\n";
}

See Introduction to SPL Iterators and Live Demo on codepad

EDIT: the alternative would be array_walk_recursive as show in Finbarr's answer below

like image 61
Gordon Avatar answered Oct 19 '22 10:10

Gordon


See array_walk_recursive - a PHP library function that recursively calls a user defined function against a provided array.

From PHP docs:

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

Output:

a holds apple
b holds banana
sour holds lemon

Note that Any key that holds an array will not be passed to the function..

EDIT: slightly less ugly example:

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits, function ($item, $key) {
    echo "$key holds $item\n";
});
?>
like image 20
Finbarr Avatar answered Oct 19 '22 11:10

Finbarr