E
E
EvgMul2017-03-13 12:32:56
PHP
EvgMul, 2017-03-13 12:32:56

How to remove duplicate elements in a multidimensional array?

Hello. I have the following problem. I have an array like this:

Array
(
    [0] => Array
        (
            [id_city] => 2096
            [ip_start] => 2.60.0.0
            [ip_end] => 2.60.255.255
            [city] => Омск
        )

    [1] => Array
        (
            [id_city] => 676
            [ip_start] => 2.61.0.0
            [ip_end] => 2.61.255.255
            [city] => Абакан
        )

    [2] => Array
        (
            [id_city] => 1706
            [ip_start] => 2.62.0.0
            [ip_end] => 2.62.255.255
            [city] => Кемерово
        )

    [3] => Array
        (
            [id_city] => 1428
            [ip_start] => 2.63.0.0
            [ip_end] => 2.63.127.255
            [city] => Красноярск
        )
...

The city field may be repeated in some elements of the array. As far as I understand array_unique()it won't work here. Can you please tell me how to remove all repetitions and leave only unique array elements in the city field?
Thanks in advance to all who respond.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-03-13
@EvgMul

// получаем уникальные ключи
$uniqueKeys = array_keys(
    array_unique(
        array_map(function($item) {
            return $item['city'];
        }, $array)
    )
);
// извлекаем в новый массив те ключи, которые были уникальными
$uniqueArray = array_filter($array, function($itemKey) {
    return in_array($itemKey, $uniqueKeys);
}, ARRAY_FILTER_USE_KEY);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question