根据键对数组进行分组并删除重复数据(2维数组)

时间:2016-03-10 10:39:07

标签: php multidimensional-array duplicates grouping

我有三个数组如下:

$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');

我想根据二维数组中的键对它们的值进行分组,以输出以下内容:

$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 个答案:

答案 0 :(得分:2)

使用PHP的array_map()函数

<textarea ng-model="yourStringArray" ng-list="&#10;" ng-trim="false"></textarea>

唯一记录链接: - https://stackoverflow.com/a/2442315/4198099

<强>输出: -

$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);

希望它会对你有所帮助: - )

答案 1 :(得分: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
        )

)