2015-05-08 120 views
2

如何從PHP中的多維數組中刪除重複值?PHP-從多維數組中刪除重複值

例陣列:

Array 
(
    [choice] => Array 
     (
      [0] => Array 
       (
        [day] => Monday 
        [value] => Array 
         (
          [0] => Array 
           (
            [name] => BI 
            [time] => 10:00 
            [location] => B123 
           ) 
          [1] => Array 
           (
            [name] => BI 
            [time] => 11:00 
            [location] => A123 
           ) 
         ) 
       ) 

      [1] => Array 
       (
        [day] => Tuesday 
        [value] => Array 
         (
          [0] => Array 
           (
            [name] => BI 
            [time] => 10:00 
            [location] => B123 
           ) 
          [1] => Array 
           (
            [name] => BI 
            [time] => 11:00 
            [location] => A123 
           ) 
         ) 
        ) 
     ) 
) 

我希望移除那些具有重複name。所以我只想每天保留一個主題。

到目前爲止我的代碼:

$taken = array(); 
foreach($subject_list['choice'][0]["value"] as $key =>$item) 
{ 
    if(!in_array($item['name'], $taken)) 
    { 
     $taken[] = $item['name']; 
    }else 
    { 
     unset($flight_list['choice'][0]["value"][$key]); 
    } 

} 

輸出上面的代碼(這顯然是錯誤的):

Array 
(
    [choice] => Array 
     (
      [0] => Array 
       (
        [day] => Monday 
        [value] => Array 
         (
          [0] => Array 
           (
            [name] => BI 
            [time] => 10:00 
            [location] => B123 
           ) 
         ) 
       ) 

      [1] => Array 
       (
        [day] => Tuesday 
        [value] => Array 
         (
          [0] => Array 
           (
            [name] => BI 
            [time] => 10:00 
            [location] => B123 
           ) 
          [1] => Array 
           (
            [name] => BI 
            [time] => 11:00 
            [location] => A123 
           ) 
         ) 
        ) 
     ) 
) 

任何人都可以幫助我,我怎麼能在Tuesday刪除同一類name

回答

3

如果你想保持第一組每個value批次中的唯一值的值爲name,然後爲此創建一個臨時容器。如果您已經推它,然後不處理任何事情,聚會後,覆蓋使用foreach批次與&參考:

foreach($subject_list['choice'] as &$items) { 
    $temp = array(); // temporary container for current iteration 
    foreach($items['value'] as $value) { 
     if(!isset($temp[$value['name']])) { // if its new 
      $temp[$value['name']] = $value; // push the batch using the key name 
     } 
    } 
    $items['value'] = $temp; // apply unique value in the end of this batch 
} 

Sample Output

0

其中$array是一個PHP變量,其中你的陣列來了

$array = array_map("unserialize", array_unique(array_map("serialize", $array))); 
-2

只是一個快速谷歌從一多維數組中刪除重複項:

<?php 
function super_unique($array) 
{ 
    $result = array_map("unserialize", array_unique(array_map("serialize", $array))); 

    foreach ($result as $key => $value) 
    { 
    if (is_array($value)) 
    { 
     $result[$key] = super_unique($value); 
    } 
    } 

    return $result; 
} 
?>