2017-03-19 67 views
0

我想根據兩個鍵(即a和b)刪除重複項,並且需要在第三個鍵即c和結果數組中添加值在索引a和b處的值應該是不重複的,並且在第三個索引上的值將被附加到新數組中。實施例陣列在下面給出: 我具有以下排列:刪除數組中的重複項並在同一索引上追加值php

陣列 ( [0] =>數組 ( 並[a] => 0 並[b] => 0 並[c] => 123 )

[1] => Array 
    (
     [a] => 1 
     [b] => 0 
     [c] => 43134 
    ) 

[2] => Array 
    (
     [a] => 0 
     [b] => 4 
     [c] => 5423 
    ) 

[3] => Array 
    (
     [a] => 0 
     [b] => 3 
     [c] => 2342 
    ) 

[4] => Array 
    (
     [a] => 0 
     [b] => 0 
     [c] => 123 
    ) 

[5] => Array 
    (
     [a] => 1 
     [b] => 0 
     [c] => 43134 
    ) 

[6] => Array 
    (
     [a] => 0 
     [b] => 4 
     [c] => 5423 
    ) 

[7] => Array 
    (
     [a] => 0 
     [b] => 3 
     [c] => 2342 
    ) 

,我想結果是這樣的:

陣 ( [0] =>數組 ( 並[a] => 0 並[b] => 0 並[c] =>數組 ( [0] => 123 [1] => 123 )

) 

[1] => Array 
    (
     [a] => 1 
     [b] => 0 
     [c] => Array 
      (
       [0] => 43134 
       [1] => 43134 
      ) 

    ) 

[2] => Array 
    (
     [a] => 0 
     [b] => 4 
     [c] => Array 
      (
       [0] => 5423 
       [1] => 5423 
      ) 

    ) 

[3] => Array 
    (
     [a] => 0 
     [b] => 3 
     [c] => Array 
      (
       [0] => 2342 
       [1] => 2342 
      ) 

    ) 

回答

0

迭代陣列之上,跟蹤元件已經看到並追加「c」的元素添加到原始數組,如果你已經看到之前(a/b的組合的元件) - 作爲一項功能 - 如果您不需要,請直接使用$flattened將其填充到一個函數中。

$result = array(); 

for ($i = 0; $i < count($arr); $i++) 
{ 
    $a = $arr[$i]['a']; 
    $b = $arr[$i]['b']; 

    if (isset($result[$a][$b])) 
    { 
     // append the 'c' value 
     $result[$a][$b]['c'][] = $arr[$i]['c']; 
     // we've already seen the a/b combo 
     continue; 
    } 

    // convert 'c' key to an array 
    $arr[$i]['c'] = array($arr[$i]['c']); 

    // keep the result 
    $result[$a][$b] = $arr[$i]; 
} 

$flattened = array(); 

// flatten the a/b structure to only keep the elements themselves 
foreach ($result as $a => $b_level) { 
    foreach ($b_level as $b => $element) { 
     $flattened[] = $element; 
    } 
} 

return $flattened; 
+0

'c'指數的值永遠不會相同 – user1888781

+0

但是關鍵是一樣的吧?你的例子表明你只是重複相同的'c'值..你的意思是追加所有下列已經存在的條目的c值,而不只是重複元素? – MatsLindh

+0

是啊...我希望他們追加...在例子中他們是相同的,但在真正的問題,這些是不同的..我想a和b索引以及 – user1888781