2017-08-22 195 views
-2

我有這樣的陣列(更多更長的 - 唯一部分)。陣列,總和值相同PHP的

[366] => Array 
    (
     [0] => 8 
     [1] => 7 
     [2] => 8 
     [3] => 9 
     [4] => 8 
    ) 

[367] => Array 
    (
     [0] => 8 
     [1] => 9 
     [2] => 9 
     [3] => 10 
     [4] => 10 
     [5] => 9 
     [6] => 8 
     [7] => 9 
     [8] => 10 
     [9] => 10 
     [10] => 11 
     [11] => 10 
     [12] => 11 
     [13] => 11 
     [14] => 10 
     [15] => 9 
     [16] => 10 
     [17] => 8 
     [18] => 10 
    ) 

的密鑰必須保持(有一個ID)。我想總結foreach的值(在這個例子中,值是幾代人)。因此,第8代是數3倍的366

預計於ID 366:7 - 1,8 - 3倍,9 - 1x或

[366] => Array 
    (
    [7] => 1 
    [8] => 3 
    [9] => 1 
    ) 

    [367] => Array 
    (
    [8] => 3 
    [9] => 5 
    [10] => 8 
    [11] => 3 
    ) 

的每一個建議是歡迎和讚賞!

I'm始終停止使用數字鍵或在foreach ...嘗試代碼從來就一個:

$outdams = array(); 
foreach ($dams as $key => $value) { 
    foreach ($value as $key2 => $value2) { 
     $index = $value2; 
     if (array_key_exists($index, $outdams)) { 
      $outdams[$index]++; 
     } else { 
      $outdams[$index] = 1; 
     } 
    } 
} 
+0

你能告訴我們你的」以前試過嗎? – Veve

+0

納入問題 – Shakki

回答

3

檢查這個代碼

<?php 
$data = array(366=>array(8,7,8,8,9), 
       367=>array(8,9,13,14,17,14)); 
echo "<pre>"; print_r($data); 

$response = array(); 
foreach ($data as $outerkey => $outerData){ 
    foreach ($outerData as $innerkey => $innerData){ 
     //echo "<pre>"; print_r($innerData); 
     if(array_key_exists($innerData, $response[$outerkey])){ 
      $response[$outerkey][$innerData] ++; 
     }else{ 
      $response[$outerkey][$innerData] = 1; 
     } 
    } 
} 
echo "<pre>"; print_r($response); 

?> 
+0

作品完美,謝謝! – Shakki