2014-02-12 78 views
1

計數相同的值,我想去多維數組的最深/最後一級計算相同的值:PHP:在多維數組

Array 
(
[svote001] => Array 
    (
     [0] => 006 
     [1] => 006 
     [2] => 007 
    ) 

[svote002] => Array 
    (
     [0] => 000 
     [1] => 000 
     [2] => 000 
    ) 

[svote003] => Array 
    (
     [0] => 002 
     [1] => 003 
     [2] => 001 
    ) 
) 

轉換爲

Array 
(
[svote001] => Array 
    (
     [006] => 2 
     [007] => 1 
    ) 

[svote002] => Array 
    (
     [000] => 3 
    ) 

[svote003] => Array 
    (
     [001] => 1 
     [002] => 1 
     [003] => 1 
    ) 
) 

的計數值應另外從高到低排序。

+0

該數組是否始終爲二維? – Flixer

+0

是的,數組始終是二維的,所有「內部」數組的值都是相同的:所有3個值或4或5 ... –

回答

6
foreach($array as $k => $v) { 
    $result[$k] = array_count_values($v); 
    arsort($result[$k]); 
} 
  • 循環通過陣列(暴露鍵)來訪問每個內陣列
  • 計數內數組的值(值將是關鍵和計數會值)
  • 排序由保留鍵的值(計數)
2

這應該符合您的需要:

<?php 

$a = array(
    'svote001' => array("006", "006", "007"), 
    'svote002' => array("000", "000", "000"), 
    'svote003' => array("003", "001", "001"), 
); 
$resultArray = array(); 

foreach ($a as $arrayName => $arrayData){ 
    $resultArray[$arrayName] = array(); 
    foreach ($arrayData as $value){ 
     if (empty($resultArray[$arrayName][$value])){ 
      $resultArray[$arrayName][$value] = 1; 
     }else{ 
      $resultArray[$arrayName][$value]++; 
     } 
    } 
    arsort($resultArray[$arrayName]); 
} 

var_dump($resultArray); 

編輯: AbraCadaver解決方案要好得多,用這一個。無論如何,我會讓答案留在這裏。