开发者

PHP COUNT_RECURSIVE only count non-array values?

I have a multidimensional开发者_高级运维 array to the tune of $doclist['area']['source'][#]['type']

I would like to get a number of all entries of ['type'] = "title" that are not empty.

Is there a simple way of doing it?

While I am at it, is there a way to get a number of all entries of ['type'] = "title" AND ['area'] = "something" that are not empty?


Assuming by 'area' and 'source' you mean arbitrary strings, you could nest a few loops like so:

$num_titles = 0;
foreach ($doclist as $area => $arr1) {
    foreach ($arr1 as $source => $arr2) {
        foreach ($arr2 as $k => $arr3) {
            if (isset($arr3['title']) && strlen(trim($arr3['title'])))
                $num_titles++;
        }
    }
}
print "Titles: {$num_titles}\n";
print "Areas: " . sizeof($doclist) . "\n";


Here's the function that I wrote based on rfausak's response:

function countdocs($arr,$x="",$y="") {
        if (($x) && ($y)) {
            return count($arr[$x][$y]);
        } else if ($x) {
            $r=0;
            foreach ($arr[$x] as $arr1) {
                $r+=count($arr1);
            }
            return $r;
        } else {
            $r=0;
            foreach ($arr as $arr1) {
                foreach ($arr1 as $arr2) {
                    $r+=count($arr2);
                }
            }
            return $r;
        }
    }

I thought that someone may find it useful.


$ships = array(
    "Passenger ship" =>
        array("Yacht", "Liner", "Ferry"),
    "War ship" =>
        array("Battle-wagon", "Submarine", "Cruiser"),
    "Freight ship" =>
        array("Tank vessel", "Dry-cargo ship", "Container
      cargo ship")
);

function myCount($var, $i = 0){
    $cnt = 0;
    foreach ($var as $v) {
        if (is_array($v) and $i)
            $cnt += myCount($v, 0);
        $cnt++;
    }
    return $cnt;
}
echo myCount($ships, 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜