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
)
)
)
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With