array unique php не работает

Как использовать array unique для массива массивов?

у меня есть массив

Как вы можете видеть ключ 0 такая же как 1,3 и 4. И ключ 2 отличается от них всех.

при запуске функции array_unique на них остается только

есть идеи, почему array_unique работает не так, как ожидалось?

5 ответов

потому что array_unique сравнивает элементы с помощью сравнения строк. От docs:

вы можете сделать то, что вы хотите сделать используя следующее:

вот как это работает:

каждый элемент массива сериализуется. Этот будет уникальным на основе массива содержание.

array_intersect_key возьмем ключи от уникальных предметов из функция map / unique (поскольку ключи исходного массива сохранены) и pull они из твоего первоисточник матрица.

array_unique() поддерживает только многомерные массивы в PHP 5.2.9 и выше.

, вы можете создать хэш-массива и проверить его на уникальность.

вот улучшенная версия @ryeguy это:

во-первых, он не делает ненужных сериализации. Во-вторых, иногда атрибуты могут отличаться, даже если id один и тот же.

array_unique deosn не работает рекурсивно, поэтому он просто думает: «это все Array s, давайте убьем всех, кроме одного. поехали!»

быстрый ответ (TL;DR)

Подробный Ответ!—5—>

контекст

решение

example01 ;; DeveloperMarsher начинает с переменной данных tabluar, которая выглядит следующим образом

example01 ;; DeveloperMarsher может извлекать различные значения с помощью цикла foreach, который отслеживает увиденные значения

Источник

array_unique

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_unique — Убирает повторяющиеся значения из массива

Описание

Принимает входной массив array и возвращает новый массив без повторяющихся значений.

Обратите внимание, что ключи сохранятся. Если в соответствии с заданными flags несколько элементов определяются как идентичные, то будут сохранены ключ и значение первого такого элемента.

Список параметров

Можно использовать необязательный второй параметр flags для изменения поведения сортировки с помощью следующих значений:

Читайте также:  Steam exe что это за процесс

Возвращаемые значения

Возвращает отфильтрованный массив.

Список изменений

Примеры

Пример #1 Пример использования array_unique()

Результат выполнения данного примера:

Пример #2 array_unique() и типы:

Результат выполнения данного примера:

Примечания

Замечание: Обратите внимание, что array_unique() не предназначена для работы с многомерными массивами.

Смотрите также

User Contributed Notes 41 notes

Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code

Code :
My array is like this,

In reply to performance tests array_unique vs foreach.

In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here;
http://sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1

$max = 770000; //large enough number within memory allocation
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here’s my version for you:

$array_of_objects = [new Foo ( 2 ), new Foo ( 1 ), new Foo ( 3 ), new Foo ( 2 ), new Foo ( 2 ), new Foo ( 1 )];

It’s often faster to use a foreache and array_keys than array_unique:

For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.

I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

$raw_array = array();
$raw_array [ 1 ] = ‘abc@xyz.com’ ;
$raw_array [ 2 ] = ‘def@xyz.com’ ;
$raw_array [ 3 ] = ‘ghi@xyz.com’ ;
$raw_array [ 4 ] = ‘abc@xyz.com’ ; // Duplicate

Case insensitive; will keep first encountered value.

Simple and clean way to get duplicate entries removed from a multidimensional array.

Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

Читайте также:  основы обучения незрячих детей

It simply compares the number of elements between the original array and the array_uniqued array.

The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me:

?>

The above code returns an array which is both unique and sorted from zero.

recursive array unique for multiarrays

This is a script for multi_dimensional arrays

My object unique function:

another method to get unique values is :

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love

Another form to make an array unique (manual):

Array
(
[0] => Array
(
[0] => 40665
[1] => 40665
[2] => 40665
[3] => 40665
[4] => 40666
[5] => 40666
[6] => 40666
[7] => 40666
[8] => 40667
[9] => 40667
[10] => 40667
[11] => 40667
[12] => 40667
[13] => 40668
[14] => 40668
[15] => 40668
[16] => 40668
[17] => 40668
[18] => 40669
[19] => 40669
[20] => 40670
[21] => 40670
[22] => 40670
[23] => 40670
[24] => 40671
[25] => 40671
[26] => 40671
[27] => 40671
[28] => 40671
)

[1] => Array
(
[0] => 40672
[1] => 40672
[2] => 40672
[3] => 40672
)

0
0 => 40665
4 => 40666
8 => 40667
13 => 40668
18 => 40669
20 => 40670
24 => 40671

saludos desde chile.

[Editor’s note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name]

Читайте также:  магия в террарии с чего начать

You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments!

Compared to the built in function it is 20x faster! (2x faster than the solution in the comments).

I found the simplest way to «unique» multidimensional arrays as follows:

?>

As you can see «b» will be removed without any errors or notices.

Here’s the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:

Problem:
I have loaded an array with the results of a database
query. The Fields are ‘FirstName’ and ‘LastName’.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array. For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Another way to ‘unique column’ an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.

I hope that the function will help someone

# move to the next node
continue;

# increment depth level
$l ++;

Источник

Образовательный портал