2010-04-07 116 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