PHP数组唯一值

时间:2013-05-03 11:22:52

标签: php arrays array-unique

我有一个像这样的数组

Array
(
    [0] => Array
        (
            [id] => BA
            [name] => British Airways
        )

    [1] => Array
        (
            [id] => BA
            [name] => British Airways
        )

    [2] => Array
        (
            [id] => LA
            [name] => Lanchile
        )

    [3] => Array
        (
            [id] => LA
            [name] => Lanchile
        )

    [4] => Array
        (
            [id] => BA
            [name] => British Airways
        )

    [5] => Array
        (
            [id] => BA
            [name] => British Airways
        )

)

我希望得到

Array
(
    [0] => Array
        (
            [id] => BA
            [name] => British Airways
        )

    [1] => Array
        (
            [id] => LA
            [name] => Lanchile
        )
)

但在使用array_unique函数后,我所拥有的只是

Array
(
    [0] => Array
        (
            [id] => BA
            [name] => British Airways
        )

)

我做错了什么?

4 个答案:

答案 0 :(得分:18)

array_unique(my_array, SORT_REGULAR)

根据评论的要求。 :)

答案 1 :(得分:4)

如上所述,array_unique不支持多维数组,但您可以迭代数据并构建自己的

<?php
$airlines = array(
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
);
$tmp = array();
foreach ($airlines as $item) {
    if (!in_array($item['id'], $tmp)) {
        $unique[] = $item;
        $tmp[] = $item['id'];
    }
}

var_dump($unique); // $unqiue will have your desired results in it var_dump was just for testing

答案 2 :(得分:2)

 array_unique is not intended to work on multi dimensional arrays.

你需要循环数组

array_unique

答案 3 :(得分:1)

$airlines = array(
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
    array('id' => 'BA', 'name' => 'British Airways'),
    array('id' => 'LA', 'name' => 'Lanchile'),
);


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

var_dump($unique);