如何组合3个数组并删除重复?

时间:2013-02-01 05:41:49

标签: php arrays

我有3个阵列。我需要使用Names作为键来组合它们,删除重复项(名称重复);只有最有价值的东西必须保留(基于销售数组的高价值)。我想知道是否有任何简单的方法来做到这一点。我所有的想法都是几个无聊的foreach操作。  

  [Names] => Array
        (
            [0] => Adrew Watson
            [1] => Maria Jones
            [2] => Adrew Watson
        )

[sales] => Array
    (
        [0] => 12,000.00
        [1] => 11,900.00
        [2] => 11,800.00
    )

[time] => Array
    (
        [0] => 31-Jan-13    
        [1] => 30-Jan-13    
        [2] => 29-Jan-13    
    )

输出应该是这样的:

{{1}}

我认为这将是一个关联数组,其中重复项被“value”删除。请注意,每个数组的值(例如销售额)已经订购了DESC

2 个答案:

答案 0 :(得分:3)

// Assumed from your output the arrays have the indexes Names, sales and time
$names = array('Names' => array('Adrew Watson','Maria Jones','Adrew Watson'));
$sales = array('sales' => array('12,000.00','11,900.00','11,800.00'));
$time = array('time' => array('31-Jan-13','30-Jan-13','29-Jan-13'));
$new = array();

foreach ($names['Names'] as $key => $value)
{
    if (isset($new[$value])) continue; // if already exists, skip

    $new[$value] = array(
        'sales' => $sales['sales'][$key],
        'time' => $time['time'][$key]);
}

print_r($new);

输出:

Array
(
    [Adrew Watson] => Array
        (
            [sales] => 12,000.00
            [time] => 31-Jan-13
        )

    [Maria Jones] => Array
        (
            [sales] => 11,900.00
            [time] => 30-Jan-13
        )

)

根据您的以下评论:

如果你想从数组中删除Name,你可以这样做 AFTER 运行上面的代码,例如:

unset($new['Maria Jones']); // remove Maria Jones

答案 1 :(得分:1)

这可以通过array_merge而不是rray_unique

来完成
<?php
$array1 = array("orange", "apple", "grape");
$array2 = array("peach",  "plumb","apple");
$array3 = array("lemon", "plumb");
$newArray = array_merge($array1, $array2, $array3);

$result = array_unique($newArray);
print_r($result);

Live example