Littlebobbydroptables
Littlebobbydroptables

Reputation: 3731

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?

Upvotes: 6

Views: 31226

Answers (4)

diegoperini
diegoperini

Reputation: 1806

array_unique(my_array, SORT_REGULAR)

As requested in comments. :)

Upvotes: 19

Shijin TR
Shijin TR

Reputation: 7768

 array_unique is not intended to work on multi dimensional arrays.

You need to loop the array

array_unique

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212412

$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);

Upvotes: 1

fullybaked
fullybaked

Reputation: 4127

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

Upvotes: 4

Related Questions