消除多维数组中的重复值

时间:2013-02-22 03:45:54

标签: php arrays multidimensional-array

我想知道消除数组中重复项的最佳方法是什么?目前我正在运行一个foreach循环来实际获取这个数组,有没有办法说,如果id已经存在,不要插入到数组中?

foreach($categories2Sugg as $Category2Sugg)
{

    $category_stringArray2Sugg[] = array("id"=>$Category2Sugg->id,"name"=>$Category2Sugg->name,"pluralName"=>$Category2Sugg->pluralName,"shortName"=>$Category2Sugg->shortName);      

}


Array
(
    [0] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [1] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [2] => Array
        (
            [id] => 4bf58dd8d48988d16c941735
            [name] => Burger Joint
            [pluralName] => Burger Joints
            [shortName] => Burgers
        )

    [3] => Array
        (
            [id] => 4bf58dd8d48988d14e941735
            [name] => American Restaurant
            [pluralName] => American Restaurants
            [shortName] => American
        )
)

如果这个数组已经存在,或者更容易做另一个函数,只需删除一些值来输出一个新数组?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试array_unique php功能,这将有所帮助。

同时尝试

$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));

echo "<pre>";
print_r($unique);
echo "</pre>";

以上代码经过测试。

完成经过测试的代码

<?php
$array = array
(
    '0' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '1' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '2' => array
    (
        'id' => '4bf58dd8d48988d16c941735',
        'name' => 'Burger Joint',
        'pluralName' => 'Burger Joints',
        'shortName' => 'Burgers'
    ),
    '3' => array
    (
        'id' => '4bf58dd8d48988d14e941735',
        'name' => 'American Restaurant',
        'pluralName' => 'American Restaurants',
        'shortName' => 'American'
    )
);

$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));

echo "<pre>";
print_r($unique);
?>

干杯。