Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Iterate multi-dimensional array

How can I iterate through this multidimensional array and return the count of positive numbers and the count of negative numbers. The answer should be 1 positive and 5 negative. Thanks.

Array
(
[Nov 18, 2011] => Array
    (
        [C] => Array
            (
                [C] => Array
                    (
                        [T] => -1324.388328
                    )
                [S] => Array
                    (
                        [T] => -249.976472
                    )
            )
    )
[Dec 24, 2011] => Array
    (
        [C] => Array
            (
                [C] => Array
                    (
                        [T] => -2523.107928
                    )
                [S] => Array
                    (
                        [T] => 103.533528
                    )
            )
    )
[Dec 27, 2011] => Array
    (
        [C] => Array
            (
                [C] => Array
                    (
                        [T] => -4558.837928
                    )
                [S] => Array
                    (
                        [T] => -1639.376472
                    )
            )
    )
)
like image 695
DanielAttard Avatar asked Jun 08 '26 04:06

DanielAttard


1 Answers

You could also use SPL's RecursiveIteratorIterator in combination with RecursiveArrayIterator, with something like this:

$pos = $neg = 0;
foreach( new RecursiveIteratorIterator( new RecursiveArrayIterator( $data ) ) as $item )
{
    if( !is_numeric( $item ) ) continue;

    $item < 0 ? $neg++ : $pos++;
}
var_dump( $pos, $neg );

Where $data represents your multidimensional array. RecursiveIteratorIterator defaults to only iterating, what are called, the leaves (the items that don't have any children). As a safety measure I still have incorporated a test to check whether the item is indeed a numeral value.

like image 141
Decent Dabbler Avatar answered Jun 10 '26 19:06

Decent Dabbler