php - Get sum of all the data inside an multidimensional array recursively : -
i've array :
array ( [self] => folder [my_data] => array ( ) [18] => array ( [self] => folder aa [my_data] => array ( [0] => stdclass object() ) [20] => array ( [self] => folder aa [my_data] => array ( [0] => stdclass object() ) [21] => array )
i want total number of records in of present in 'my_data
'. i've created function call recursively add count :
function getdocumentcount($tab, $count = 0) { foreach ($tab $subtabkey => $subtabvalue) { if ($subtabkey == 'my_data') { $count += count($subtabvalue); } if ( count($tab) > 2 && $subtabkey != 'self' && $subtabkey != 'my_data' ) { $count += getdocumentcount($subtabvalue, $count); } } return $count; }
but function returning 0. above example should return 2
edit : should return 5 returning 9
array ( [self] => main folder 22 [my_data] => array ( ) [17] => array ( [self] => new sub [my_data] => array ( [0] => stdclass object() [1] => stdclass object() ) ) [8] => array ( [self] => sub folder 21 [my_data] => array ( ) [9] => array ( [self] => sub folder 211 [my_data] => array ( [0] => stdclass object() [1] => stdclass object() [2] => stdclass object() ) ) ) )
you calculated first dimension of array length of my_data 0, $count 0. though calculated inner dimmension of array, didnot sum output of them. have sum output of inner output.
function getdocumentcount($tab, &$count) { foreach ($tab $subtabkey => $subtabvalue) { if ($subtabkey == 'my_data') { $count += count($subtabvalue); } if ( count($tab) > 2 && $subtabkey != 'self' && $subtabkey != 'my_data' ) { getdocumentcount($subtabvalue, $count); } } }
use with:
$count = 0; getdocumentcount($tab, $count); echo $count;
Comments
Post a Comment