我有一個多維數組的$doclist['area']['source'][#]['type']
PHP COUNT_RECURSIVE只計算非數組值?
調我想獲得一些非空的['type'] = "title"
所有條目。
有沒有簡單的方法呢?
雖然我在這裏,有沒有辦法讓['type'] = "title"
和['area'] = "something"
的所有條目都不是空的?
我有一個多維數組的$doclist['area']['source'][#]['type']
PHP COUNT_RECURSIVE只計算非數組值?
調我想獲得一些非空的['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);
一些代碼示例? – J0HN