Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array unique values

I have an array like this

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
        )

)

and i want to get

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

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

but after using array_unique function, all i have is

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

)

what am i doing wrong?

like image 256
MyMomSaysIamSpecial Avatar asked May 03 '13 11:05

MyMomSaysIamSpecial


2 Answers

array_unique(my_array, SORT_REGULAR)

As requested in comments. :)

like image 163
diegoperini Avatar answered Oct 09 '22 06:10

diegoperini


As mentioned array_unique doesn't support multi dimensional arrays, but you could iterate over the data and build your own

<?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
like image 34
fullybaked Avatar answered Oct 09 '22 06:10

fullybaked