2010-04-07 159 views
2

我有一个多维数组,我会有多个数组。其中一些数组也包含多个数组,并且我想要统计第二个数组中有多少个数组(日期)。如何计算多维数组中有多少个数组具有相同名称的多维数组?

这是多维数组结构的一个例子:

$_SESSION['final_shipping'][04/03/2010][book] 
$_SESSION['final_shipping'][04/12/2010][magazine] 
$_SESSION['final_shipping'][04/12/2010][cd] 

这是我目前使用的计算有多少第二阵列(带有日期)存在的foreach语句。

foreach($_SESSION['final_shipping'] as $date_key => $date_value) { 
    foreach ($date_value as $product_key => $product_value) { 
     echo 'There are ' . count($date_key) . ' of the ' . $date_key . ' selection.<br/>'; 
    } 
} 

它当前输出该:

有所述04/03/2010选择的1。
2010年4月12日的选择中有1个。
2010年4月12日的选择中有1个。

我会把它想输出这样的:

还有的选择04/03/2010 1。
2010年4月12日的选择中有2个。

回答

4

请致电count()$date_value取而代之,因为您要计算映射到该键的数组值的项数,而不是键的本身大小。

foreach($_SESSION['final_shipping'] as $date_key => $date_value) { 
    echo 'There are ' . count($date_value) . ' of the ' . $date_key . ' selection.<br/>'; 
} 
+0

我太亲近了。非常感谢! – zeckdude 2010-04-07 10:14:34

2

你指望它需要的错varibale是$date_value

​​
0

对于多维数组是这样的:

$data = array(
    'item1' => array(
     'item1-1' => array('foo' => 1,'bar' => 1), 
     'item1-2' => array('bar' => 1), 
    ), 
    'item2' => array( 
     'item2-1' => array('foo' => 1) 
    ) 
); 

您可以创建一个RecursiveIteratorIteratorRecursiveArrayIterator

$it = new RecursiveIteratorIterator(
     new RecursiveArrayIterator($data), 
     RecursiveIteratorIterator::SELF_FIRST); 

,然后遍历它很容易与foreach

foreach($it as $key => $val) { 
    if(is_array($val)) { 
     printf('There is %d of %s%s', count($val), $key, PHP_EOL); 
    } 
} 

接收

There is 2 of item1 
There is 2 of item1-1 
There is 1 of item1-2 
There is 1 of item2 
There is 1 of item2-1 

可以限制这种只与

foreach($it as $key => $val) { 
    if(is_array($val) && $it->getDepth() === 1) { 
     printf('There is %d of %s%s', count($val), $key, PHP_EOL); 
    } 
} 

返回一定深度的阵列接收

There is 2 of item1-1 
There is 1 of item1-2 
There is 1 of item2-1 
+0

很高兴看到这种方法出现在答案中,但给出的例子并不特别适用于这个问题。 – salathe 2010-04-07 10:04:53

+0

@salathe你觉得缺少什么? – Gordon 2010-04-07 10:06:44

+0

我想最主要的是满足“统计第二个数组中有多少个数组(日期)”的请求,而不是一个通用的count-all-level解决方案。 – salathe 2010-04-07 10:14:20