multidimensional array - php 5.3 convert array_walk_recursive -


i have following code, , i'd away call-time pass-by-reference, (to convert 5.2 5.3) i'm not sure sure correct way (class, global variable, ?)

here codepad should have in http://codepad.org/ombgfpmr

<?php  function count_things($item, $key, $total) {     $total++; }  $counts = array(100 => 1,             101 => 1,             102 => array(                 106 => 1,                 107 => 1             ),             103 => 1,             104 => 1,             105 => array(                 108 => 1,                 109 => array(                     110 => 1,                     111 => 1,                     112 => 1                 )             )         );  foreach($counts $key => $count) {     $total = 0;      if(is_array($count)) {             $total++;             /* below logic error. array elements contain arrays not                callback function called on them. therefore, children children                of own not counted. in output of paste,                final key, $final_counts[105]['total'], should have value of 6,                has value of 5. */     array_walk_recursive($count, 'count_things', &$total); } else {             $total = $count;     }      $final_counts[$key]['total'] = $total; }     print_r($final_counts);  ?> 

output looks like:

array ( [100] => array     (         [total] => 1     )  [101] => array     (         [total] => 1     )  [102] => array     (         [total] => 3     )  [103] => array     (         [total] => 1     )  [104] => array     (         [total] => 1     )  [105] => array     (         [total] => 5     )  ) 

you can use count count_recursive flag.

you should use closures this, these introduced in 5.3.0 should work.

<?php  $counts = array(     100 => 1,     101 => 1,     102 => array(         106 => 1,         107 => 1     ),     103 => 1,     104 => 1,     105 => array(         108 => 1,         109 => array(             110 => 1,             111 => 1,             112 => 1         )     ) );  $final_counts = array();  foreach($counts $key => $count) {      if(is_array($count)) {         $total = 1;         array_walk_recursive($count, function() use (&$total) {             $total++;         });     } else {         $total = $count;     }      $final_counts[$key]['total'] = $total; }  print_r($final_counts); 

i might able provide better solution if put problem in context.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -