2016-03-10 113 views
-2

我有三個陣列如下:組陣列和刪除重複(2個維陣列)

$a=Array ([0] => 'member0' [1] => 'member1' [2] => 'member2' [3] => 'member1'); 
$b=Array ([0] => 'id0' [1] => 'id1' [2] => 'id2' [3] => 'id1'); 
$c=Array ([0] => 'tf0' [1] => 'tf1' [2] => 'tf2' [3] => 'tf1'); 

我想組根據其在2維陣列來輸出鍵它們的值以下:

$2dim_array=array(array('member0','id0','tf0'),array('member1','id1','tf1'),array('member2','id2','tf2'),array('member1','id1','tf1')); 

後,我想刪除以前的2維數組並輸出像這裏面的任何重複陣列:

$remove_duplicates=array(array('member0','id0','tf0'),array('member1','id1','tf1'),array('member2','id2','tf2')); 

我該怎麼做?

注意:這個例子的數組每個只包含3個元素,但是我的數組的長度可以是可變的(未定義鍵的數量)。

+2

不知道爲什麼我在這個問題上被拒絕了......我認爲它對其他人也有用...... – Sarah

+0

同意你的意見。它肯定會幫助其他人:-) –

回答

1

你可以根據按鍵使用array_map()爲組:

$a = array('member0','member1','member2','member1'); 
$b = array('id0','id1','id2','id1'); 
$c = array('tf0','tf1','tf2','tf1'); 

$merge = array_map(function($a1, $b1, $c1){ 
    return array($a1, $b1, $c1); 
}, $a, $b, $c); 

爲了去除重複的記錄,你可以使用array_map()array_unique()

// remove duplicates by using array_map() and `array_unique()` for multidimensional array 
$duplicateRemoved = array_map("unserialize", array_unique(array_map("serialize", $merge))); 

// rearrange the array 
$rearrangeArray = array_values($duplicateRemoved); 

echo "<pre>"; 
print_r($rearrangeArray); 

結果:

Array 
(
    [0] => Array 
     (
      [0] => member0 
      [1] => id0 
      [2] => tf0 
     ) 

    [1] => Array 
     (
      [0] => member1 
      [1] => id1 
      [2] => tf1 
     ) 

    [2] => Array 
     (
      [0] => member2 
      [1] => id2 
      [2] => tf2 
     ) 

) 
+1

upvoted爲您的重新排列索引,但我仍然不知道它的必要性,但我知道如果你已經添加它,那麼一定有一個原因;-) –

2

使用PHP的array_map()功能

$a = ['member0','member1','member2','member1']; 
$b = ['id0','id1','id2','id1']; 
$c = ['tf0','tf1','tf2','tf1']; 

// run three arrays in loop with array_map 
$result = array_map(function($a1, $b1, $c1){ 
     return [ $a1, $b1, $c1]; 
}, $a, $b, $c); 

// get unique records 
$result = array_map('unserialize', array_unique(array_map('serialize', $result))); 
echo '<pre>'; print_r($result); 

唯一的記錄鏈接: - https://stackoverflow.com/a/2442315/4198099

輸出: -

Array 
(
    [0] => Array 
     (
      [0] => member0 
      [1] => id0 
      [2] => tf0 
     ) 

    [1] => Array 
     (
      [0] => member1 
      [1] => id1 
      [2] => tf1 
     ) 

    [2] => Array 
     (
      [0] => member2 
      [1] => id2 
      [2] => tf2 
     ) 

) 

希望它會幫助你:-)

+0

終於你更新了獨特記錄的答案:) – devpro

+1

@devpro:是我的朋友。我錯過了它在前面的鏡頭:-) –

+0

現在它很好,我的投票爲你, – devpro