时间:2021-07-01 10:21:17 帮助过:4人阅读
'asia'=>array(
'china'=>array(
'beijing',
'shanghai',
'tianjin',
'hangzhou'
),
'japan'=>array(
'tokyo',
'hokkaido',
'nagasaki'
)
),
'europe'=>array(
'france'=>array(
'paris',
'lyon'
),
'spain'=>array(
'madrid',
'barcelona',
'sevilla'
)
),
'australia'=>array(
'australia'=>array(
'sydney',
'melbourne'
)
)
);
返回 3,5,14
没有代码有思路也可以
例如
$earth = array(
'asia'=>array(
'china'=>array(
'beijing',
'shanghai',
'tianjin',
'hangzhou'
),
'japan'=>array(
'tokyo',
'hokkaido',
'nagasaki'
)
),
'europe'=>array(
'france'=>array(
'paris',
'lyon'
),
'spain'=>array(
'madrid',
'barcelona',
'sevilla'
)
),
'australia'=>array(
'australia'=>array(
'sydney',
'melbourne'
)
)
);
返回 3,5,14
我觉得你要做这种统计的话,应该只能用递归的方式了
// $array:要统计的数组,$i为第几维,$count维上层统计
function count_array($array,$i=1,$count = array()) {
$n = 0;
if(isset($count[$i])) {
$n = $count[$i];
}
$count[$i] = count($array) + $n;
$i += 1;
foreach($array as $item) {
if(is_array($item)) {
$count = sp_arr($item,$i,$count);
}
}
return $count;
}
$array = array(
'a' => array(
'b' => 'c',
'd' => 'e',
'f' => 'g',
),
'h' => array(
'i' => array(
'j' => 'k',
'l' => 'm',
'n' => array(
'o' => 'p',
'q' => 'r'
)
)
)
);
$count = count_array($array);
var_dump($count);
// result:
/**
*array (size=4)
* 1 => int 2
* 2 => int 4
* 3 => int 3
* 4 => int 2
*/
好吧,我写个循环的(可优化,自行优化,因为我对PHP不是很熟)
简单来说是一个广度优先搜索(稍微优化一下的队列,如果改成栈就是深度优先)
function count_array($array)
{
$count = array();
$level = 0;
$tfifo = $array;
do{
$fifo = $tfifo;
$tfifo = array();
$count[$level] = 0;
foreach($fifo as $item){
$count[$level]++;
if(is_array($item)) {
foreach($item as $subitem){
$tfifo[] = $subitem;
}
}
}
$level++;
}while(count($tfifo)>0);
return $count;
}
arr{x}{y}[z]
第三维度的元素个数不就是arr{x}{y}.length么?
依次类推不就行了?
还是说我对你的问题理解上有错误?
用中括号刚前面的没出来,,,
$num = array() ;
function get_num($fat,$num){
$num[] = count($fat) ;
$sun = array() ;
foreach ($fat as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$sun[] = $v ;
}
}
}
if ($sun) {
return get_num($sun,$num) ;
}
return $num ;
}
// var_dump(get_num($arr,$fat)) ;
大神解答,发出来给大家分享一下