2017-06-15 61 views
3

試圖從嵌套數組中刪除相同的同胞(葉子)/相同的數組。PHP - 刪除數組中相同的同胞(葉)(從數組中刪除相同的數組)

e.g

$data = [ 
     'test' => [ 
       'a' => [ 
         'b' => 'something', 
         5 => [ 
           'a' => [ 
             1 => 'test1', 
             19 => 'test2', 
             6 => 'test3', 
           ], 
           0 => 'test', 
         ], 
       ], 
       'b' => 1, 
       2 => [ 
         3 => 'something', 
         5 => 'somethingelse', 
       ], 
       4 => 'body' 
     ], 
     'anothertest' => [ 
       'b' => 1, 
       0 => [ 
         'test' => 1, 
         2 => 'something', 
         3 => 'somethingelse', 
       ], 
       1 => [ 
         'test' => 1, 
         2 => 'something', 
         3 => 'somethingelse', 
       ], 
     ], 
]; 

Array 
(
    [test] => Array 
     (
      [a] => Array 
       (
        [b] => something 
        [5] => Array 
         (
          [a] => Array 
           (
            [1] => test1 
            [19] => test2 
            [6] => test3 
           ) 

          [0] => test 
         ) 

       ) 

      [b] => 1 
      [2] => Array 
       (
        [3] => something 
        [5] => somethingelse 
       ) 

      [4] => body 
     ) 

    [anothertest] => Array 
     (
      [b] => 1 
      [0] => Array 
       (
        [test] => 1 
        [2] => something 
        [3] => somethingelse 
       ) 

      [1] => Array 
       (
        [test] => 1 
        [2] => something 
        [3] => somethingelse 
       ) 

     ) 

) 

$數據[ 'anothertest'] [0]和$數據[ 'anothertest'] [1]是相同的,所以一個已被刪除。

帶字符串索引的數組可以跳過。

如何在foreach鍵值塊中比較一個數組與另一個數組。

我知道我可以將相同的數組與===運算符進行比較,但不知道如何在foreach循環中訪問下一個運算符。

這是我的代碼,用PSUEDOCODE塊,我不知道該怎麼做。

function cleansiblings($array) 
    { 
    foreach ($array as $key => $value) { 
       if (!is_string($key)) { 
        //PSEUDO CODE 
        //compare current $value to $value+1?? 
       } 
    } 

    } 

任何幫助表示讚賞。

感謝,

+0

您是否嘗試過array_uniq ue功能? (http://php.net/manual/en/function.array-unique.php) – janfitz

回答

0

您可以刪除多維數組重複這樣

<?php 

function get_unique($array){ 
    $result = array_map("unserialize", array_unique(array_map("serialize", $array))); 
    foreach ($result as $key => $value){ 
     if (is_array($value)){ 
      $result[$key] = get_unique($value); 
     } 
    } 
    return $result; 
} 

echo "<pre/>";print_r(get_unique($data)); 

?> 

輸出: - https://eval.in/817099

+0

謝謝!!!!作品! –

+0

@android_dev很高興幫助你:) :) –

0

要回答只是你的問題的最後一部分:您可以訪問原來的$ array在使用$ key的foreach循環中:

function cleansiblings($array) 
    { 
    foreach ($array as $key => $value) { 
      if (!is_string($key)) { 
       if (isset($array[$key+1])) { 
        // Compare $array[$key] (or $value, it is the same) with $array[$key+1] 
        // To remove item from array, just unset it: unset($array[$key]). 
        // Note that you can alter iterated array in PHP, 
        // but not in some other languages. 
       } 
      } 
    } 

}