Forum Moderators: coopster

Message Too Old, No Replies

Counting a nested array

         

salamander 80

11:41 pm on Dec 20, 2007 (gmt 0)

10+ Year Member



I have an array that's like below. As you can see, it's an array that encompasses an array (that encompasses another array, etc.) and each children contains a random number of items. Basically, for each main array, i need to go through all its children and count up how many of them contains "allday".

What's the best way to deal with the problem?


Array
(
[0] => Array
(
[children] => Array
(
[0] => Array
(
[name] => xproperties
[attributes] => Array
(
[name] => [b]allday[/b]
)
[content] =>
[children] => Array
(
[0] => Array
(
[name] => xprop
[attributes] =>
[content] => yes
)
)
)
[1] => Array
(
[name] => xproperties
[attributes] => Array
(
[name] => link
)

[content] =>
[children] => Array
(
[0] => Array
(
[name] => xprop
[attributes] =>
[content] => http://www.example.com
)

)

)
[1] => Array
(

[children] => Array
(
[0] => Array
(
[name] => id
[attributes] =>
[content] => 12345
)

and so on....

cameraman

5:07 pm on Dec 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, salamander80!

If you're running php5, have a look at array_walk_recursive() [php.net].
If you're running php4, have a look at array_walk() [php.net].

With the former, your callback function would be very simple, just incrementing a global variable:
$count = 0;
function count_allday($item,$key) {
global $count;
if($item == 'allday')
$count++;
} // end count_allday()

You can simulate the the behaviour of array_walk_recursive with array_walk by checking (inside your callback function) to see if $item is an array with is_array() [php.net] - if it is, call array_walk again on $item and specifying the same function.