2012-06-13 106 views
3

我有這樣的陣列增加它的值,分配陣列密鑰和使用相同的密鑰

array(
    [0]=>111 //id 
    [1]=>5 //value to ad 
    [2]=>3 //value to ad 
) 
array(
    [0]=>111 
    [1]=>3 
    [2]=>7 
) 
array(
    [0]=>111 
    [1]=>2 
    [2]=>1 
) 
array(
    [0]=>222 
    [1]=>5 
    [2]=>3 
) 

如何可以過濾那些陣列,其結果是每「ID」一次顯示它,並添加「值添加「如果他們有相同的」ID「。所以結果將是:

array(
    [111]=>array(
      [0]=>10 
      [1]=>11 
     ) 
    [222]=>array(
      [0]=>5 
      [1]=>3 
     ) 
) 

回答和建議感謝!

回答

2

您必須使用循環手動執行此操作。像這樣的東西應該工作:

$result = array(); 

foreach($input as $row) { 
    $id = array_shift($row); 

    foreach($row as $key => $value) { 

     $result[ $id ][ $key ] = 
      (isset($result[ $id ][ $key ]) ? 
        $result[ $id ][ $key ] + $value : 
        $value 
      ); 
    } 
} 

輸出:

array(2) { 
    [111]=> 
    array(2) { 
    [0]=> 
    int(10) 
    [1]=> 
    int(11) 
    } 
    [222]=> 
    array(2) { 
    [0]=> 
    int(5) 
    [1]=> 
    int(3) 
    } 
} 

Demo

0

代碼

// This is your input. 
$Input[] = array(
    0=>111, //id 
    1=>5, //value to ad 
    2=>3 //value to ad 
); 
$Input[] = array(
    0=>111, 
    1=>3, 
    2=>7 
); 
$Input[] = array(
    0=>111, 
    1=>2, 
    2=>1 
); 
$Input[] = array(
    0=>222, 
    1=>5, 
    2=>3 
); 

// This is your output. 
$Output = array(); 
for($i=0; $i<count($Input); $i++) 
{ 
    $id = $Input[$i][0]; 

    // If key already exists... 
    if(array_key_exists($id, $Output)) 
    { 
     // Sum it. 
     $Output[$id][0] += $Input[$i][1]; 
     $Output[$id][1] += $Input[$i][2]; 
    } 
    // If not... 
    else 
    { 
     // Initialize it. 
     $Output[$id][0] = $Input[$i][1]; 
     $Output[$id][1] = $Input[$i][2]; 
    } 
} 

// This is your output dumped. 
print_r($Output); 

輸出

Array 
(
    [111] => Array 
     (
      [0] => 10 
      [1] => 11 
     ) 

    [222] => Array 
     (
      [0] => 5 
      [1] => 3 
     ) 

) 

附加註釋

的關鍵是使用array_key_exists,以檢查是否一個索引以陣列已經存在。

1

保持簡單

foreach ($arrays as $array) { 

    $final[$array[0]] = array(
     @$final[$array[0]][0] + $array[1], 
     @$final[$array[0]][1] + $array[2] 
    ); 
} 

http://codepad.org/lCCXHjKR