我有一个多维数组$doclist['area']['source'][#]['type']
我想要得到['type'] = "title"
中所有不为空的条目的个数。
有简单的方法吗?
当我在它,是否有一种方法来获得一些['type'] = "title"
和['area'] = "something"
的所有条目不是空的?
假设'area'
和'source'
是指任意字符串,您可以嵌套几个循环,如下所示:
$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";
下面是我根据rfausak的响应编写的函数:
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;
}
}
我想也许有人会觉得有用。
$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);