删除MultiDimensional数组中的重复项并保留原始数组键值

时间:2014-08-09 13:13:32

标签: php multidimensional-array

我有这个数组

Array (
    [0] => Array ( [name] => Apple [amount] => 1)
    [1] => Array ( [name] => Apple [amount] => 2)
    [2] => Array ( [name] => Orange [amount] => 3)
    [3] => Array ( [name] => Orange [amount] => 4)
    [4] => Array ( [name] => Banana [amount] => 5)
    [5] => Array ( [name] => Pear [amount] => 6)
)

我想这样结束:

Array (
    [0] => Array ( [name] => Apple [amount] => 1)
    [2] => Array ( [name] => Orange [amount] => 3)
    [4] => Array ( [name] => Banana [amount] => 5)
    [5] => Array ( [name] => Pear [amount] => 6)
)

重要的是转换后数组键值必须相同。

目前我使用此解决方案:

$newArray = array();
$usedFruits = array();

foreach ( $originalArray AS $line ) {
    if ( !in_array($line['name'], $usedFruits) ) {
        $usedFruits[] = $line['name'];
        $newArray[] = $line;
    }
}

$originalArray = $newArray;
$newArray = NULL;
$usedFruits = NULL;

这会删除重复的数组,但它也会重置键值。

Array ( 
    [0] => Array ( [name] => Apple [amount] => 1)
    [1] => Array ( [name] => Orange [amount] => 3)
    [2] => Array ( [name] => Banana [amount] => 5)
    [3] => Array ( [name] => Pear [amount] => 6)
)

如何保留原始数组键值?

2 个答案:

答案 0 :(得分:4)

使用$key中的可选foreach()

foreach ( $originalArray AS $key => $line ) { 
    if ( !in_array($line['name'], $usedFruits) ) { 
        $usedFruits[] = $line['name']; 
        $newArray[$key] = $line; 
    } 
} 

http://codepad.org/SuClGlQW

输出:

Array
(
    [0] => Array
        (
            [name] => Apple
            [amount] => 1
        )

    [2] => Array
        (
            [name] => Orange
            [amount] => 3
        )

    [4] => Array
        (
            [name] => Banana
            [amount] => 5
        )

    [5] => Array
        (
            [name] => Pear
            [amount] => 6
        )

)

答案 1 :(得分:1)

您必须使用的是未设置功能。

unset函数从指定索引处的数组中删除项,而不重新设置数组索引。

代码如下

$originalArray = array( 
    array("name" => "Apple", "amount" => 1),
    array("name" => "Apple", "amount" => 2),
    array("name" => "Orange", "amount" => 3),
    array("name" => "Orange", "amount" => 4),
    array("name" => "Banana", "amount" => 5),
    array("name" => "Peer", "amount" => 6)
);

$seenItems = array();

foreach($originalArray as $index => $item){
    if(in_array($item["name"], $seenItems))
        unset($originalArray[$index]);
    else
        $seenItems[] = $item["name"];
}

,输出如下

array(4) {
  [0]=>
  array(2) {
    ["name"]=>
    string(5) "Apple"
    ["amount"]=>
    int(1)
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(6) "Orange"
    ["amount"]=>
    int(3)
  }
  [4]=>
  array(2) {
    ["name"]=>
    string(6) "Banana"
    ["amount"]=>
    int(5)
  }
  [5]=>
  array(2) {
    ["name"]=>
    string(4) "Peer"
    ["amount"]=>
    int(6)
  }
}