2016-07-28 102 views
1

我正在尋求一些幫助,用於計算多維數組中的值。在多維php數組中計算每個鍵值的出現

我有一個類似「barrack obama」的數組鍵,這些值將會是一長串數字。

然後下一個數組鍵可能是「另一個名字」,這些值也將是一長串數字。

最多約10個陣列鍵全部類似排列。

例的var_dump:

array(10) { ["barack obama"]=> array(4260) { [0]=> string(2) "19" [1]=> string(2) "92" [2]=> string(2) "27" [3]=> string(2) "55" [4]=> string(2) "56" [5]=> string(2) "57" [6]=> string(4) "1409" [7]=> string(4) "1384" [8]=> string(4) "1362" [9]=> string(4) "1345" [10]=> string(4) "1280" } 
["united states"]=> array(5886) { [0]=> string(2) "72" [1]=> string(2) "81" [2]=> string(2) "89" [3]=> string(2) "90" [4]=> string(2) "92" [5]=> string(2) "21" [6]=> string(2) "23" [7]=> string(2) "27" [8]=> string(2) "32" [9]=> string(2) "47" [10]=> string(2) "55" } 

我怎麼能算的時間的唯一值(數字)在我的數組鍵(地名)發生量。

因此,如果55是在這兩個「奧巴馬」和「美國」,將比分2.

理想情況下,我想只保留中出現的一個或多個鍵的值,但是我可以搞定我至少得分後得分。

回答

1

創建結果的數組。然後迭代外部數組,並在循環內迭代子數組並相應地增加結果數組:

$data = array(
    "barack obama" => array(0,50,150,250,600,900,45,150,1050), 
    "tom jones"  => array(80,120,150,75,250,80,1100,1900), 
    "bob mugabe" => array(50,120,10,0,250,900,600,45,1000,1010), 
);  

$results = array(); // create an empty array to store our results 
foreach ($data as $item): // loop the outer array 
    foreach ($item as $key => $value): // loop the inner array 
     if (array_key_exists($value,$results)){ // check if value is already in results, if not set to 1, otherwise increment 
      $results[$value] = $results[$value] + 1; 
     } else { 
      $results[$value] = 1; 
     } 

    endforeach; 
endforeach; 

// show our results array 
print "<pre>"; 
print_r($results); 
+1

謝謝 - 非常好! – feelsickened

0

迭代的多維數組這樣過來:

<?php 
$data = array(
    'barack_obama' => array('19', '92', '27', '55', '57', '1409', '1384', '1362', '1345', '1280'), 
    'united_states' => array('72', '81', '89', '90', '92', '21', '23', '27', '32', '47', '55'), 
); 

$aggregator = []; 
foreach (array_keys($data) as $i) { 
    for ($j = 0, $entryCount = count($data[$i]); $j < $entryCount; $j++) { 
     $index = $data[$i][$j]; 
     $aggregator[$index] = isset($aggregator[$index]) ? $aggregator[$index] + 1 : 1; 
    } 
} 
var_export($aggregator); 

其結果是:

array (19 => 1, 92 => 2, 27 => 2, 55 => 2, 57 => 1, 1409 => 1, 1384 => 1, 1362 => 1, 1345 => 1, 1280 => 1, 72 => 1, 81 => 1, 89 => 1, 90 => 1, 21 => 1, 23 => 1, 32 => 1, 47 => 1,)