2015-02-06 132 views
0

所以我在PHP中有這個數組。PHP合併值相同的數組

$arr = [ 
    [ 'sections' => [1], 'id' => 1 ], 
    [ 'sections' => [2], 'id' => 1 ], 
    [ 'sections' => [3], 'id' => NULL ], 
    [ 'sections' => [4], 'id' => 4 ], 
    [ 'sections' => [5], 'id' => 4 ], 
    [ 'sections' => [6], 'id' => 4 ] 
]; 

我要合併的「身份證」,並得到類似

$arr = [ 
    [ 'sections' => [1, 2], 'id' => 1 ], 
    [ 'sections' => [3], 'id' => NULL ], 
    [ 'sections' => [4, 5, 6], 'id' => 4 ] 
]; 

只是努力讓我的頭圍繞這一個。

+0

這還不清楚。也許不同的鍵名會有幫助? – 2015-02-06 16:22:01

+0

你從哪裏得到方括號?這是一個數組的完整wrogn格式! – 2015-02-06 16:28:26

+1

@ AntonyD'Andrea:你試過了嗎? PHP 5.4。 – AbraCadaver 2015-02-06 16:29:06

回答

3

我創建這個快速功能可能適合您

<?php 
// Your array 
$arr = array(
     array('elem1' => 1, 'elem2' => 1), 
     array('elem1' => 2, 'elem2' => 1), 
     array('elem1' => 3, 'elem2' => NULL), 
     array('elem1' => 4, 'elem2' => 4), 
     array('elem1' => 5, 'elem2' => 4), 
     array('elem1' => 6, 'elem2' => 4) 
); 
print_r($arr); 

function mergeBy($arr, $elem2 = 'elem2') { 
    $result = array(); 

    foreach ($arr as $item) { 
     if (empty($result[$item[$elem2]])) { 
      // for new items (elem2), just add it in with index of elem2's value to start 
      $result[$item[$elem2]] = $item; 
     } else { 
      // for non-new items (elem2) merge any other values (elem1) 
      foreach ($item as $key => $val) { 
       if ($key != $elem2) { 
        // cast elem1's as arrays, just incase you were lazy like me in the declaration of the array 
        $result[$item[$elem2]][$key] = $result[$item[$elem2]][$key] = array_merge((array)$result[$item[$elem2]][$key],(array)$val); 
       } 
      } 
     } 
    } 
    // strip out the keys so that you dont have the elem2's values all over the place 
    return array_values($result); 
} 

print_r(mergeBy($arr)); 
?> 

工作任何想法希望這會工作超過2元,你可以選擇排序什麼也....