从数组中删除特定的重复键值

时间:2015-11-18 16:08:03

标签: php arrays duplicates

我搜索并尝试了许多不同的"从数组中删除重复项#34;功能,但没有一个为我的情况。我试图从数组中删除特定的副本。

从下面我想删除重复的" PHASER 4600"

[0] => Array
    (
        [id] => 1737
        [product_name] => PHASER 4200
        [certification_date] => 3/20/12
    )

[1] => Array
    (
        [id] => 1738
        [product_name] => PHASER 4600
        [certification_date] => 3/20/12
    )

[2] => Array
    (
        [id] => 1739
        [product_name] => PHASER 4600
        [certification_date] => 3/20/12
    )

[3] => Array
    (
        [id] => 1740
        [product_name] => PHASER 4700
        [certification_date] => 3/20/12
    )

[4] => Array
    (
        [id] => 1741
        [product_name] => PHASER 4800
        [certification_date] => 3/20/12
    )

2 个答案:

答案 0 :(得分:1)

您可以将它们放入一个新数组中并在放入时进行检查以查看它是否重复。

$newArray = array();

foreach ($oldArray as $old) {
    $found = false;

    foreach ($newArray as $new) {
        if ($new['product_name'] == $old['product_name']) {
            $found = true;
        }
    }

    if (!$found) {
        array_push($newArray, $old);
    }
}

答案 1 :(得分:1)

您可以使用此功能:

function delete_duplicate_name(&$arr, $name){
    $found = false;
    foreach($arr as $key => $elm){
        if($elm['product_name'] == $name){
            if($found == true)
                unset($arr[$key]);
            else
                $found = true;
        }
    }
}
delete_duplicate_name($arr, 'PHASER 4600');
print_r($arr);