убрать вложенность массива php

array_diff

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

array_diff — Вычислить расхождение массивов

Описание

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

Массивы, с которыми идёт сравнение

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

Примеры

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

Пример #2 Пример использования array_diff() с несовпадающими типами

$source = [new S ( ‘a’ ), new S ( ‘b’ ), new S ( ‘c’ )];
$filter = [new S ( ‘b’ ), new S ( ‘c’ ), new S ( ‘d’ )];

Примечания

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

User Contributed Notes 27 notes

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.

array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

If you want a simple way to show values that are in either array, but not both, you can use this:

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case 😀

We got 2 arrays like these:

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want «.» or «..» to be in the array of files I’m creating. Here’s a simple way to remove them:

If you just need to know if two arrays’ values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:

?>

The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.

my alternative method for evaluating if two arrays contain (all) identical values:

?>

may be slightly faster (10-20%) than this array_diff method:

?>

but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().

Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().

Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().

It’s important to note that array_diff() is NOT a fast or memory-efficient function on larger arrays.

In my experience, when I find myself running array_diff() on larger arrays (50+ k/v/pairs) I almost always realize that I’m working the problem from the wrong angle.

Typically, when reworking the problem to not require array_diff(), especially on bigger datasets, I find significant performance improvements and optimizations.

If you’re not getting a count(array_diff($a1,$a2))>0 with something similar to the following arrays should use the php.net/array_diff_assoc function instead.

There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:

10x faster than array_diff

Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.

I always wanted something like this to avoid listing all the files and folders you want to exclude in a project directory.

$relevantFiles = array_diff(scandir(‘somedir’), array(‘.’, ‘..’, ‘.idea’, ‘.project));

As touched on in kitchin’s comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de’s comment of 17-Jul-2007 10:45, array_diff’s behavior may be counter-intuitive if you aren’t thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren’t in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization.

As far as a function for returning what you may be expecting, here’s one:

Resubmitting. the update for takes into account comparison issues

Computes the difference of all the arrays

I’ve found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:

Yes you can get rid of gaps/missing keys by using:

Note that array_diff is not equivalent to

The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at https://gist.github.com/wrey75/c631f6fe9c975354aec7 (including a class with an function to patch the array)

Here the basic function:

A simple multidimentional key aware array_diff function.

Based on one lad’s code, I created following function for creating something like HTML diff. I hope it will be useful.

Hi!
I tried hard to find a solution to a problem I’m going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it’s some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

so basically, I wanted to delete coincidences on both arrays.

Now, I’ve some actions to do, and I know wich one I’ve to do with the values from one array or another.
With the normal DIFF I can’t, because if I’ve an array like C=1,4, I dont know if I’ve to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don’t know wich action to apply.

So a call to this will be somethin’ like:

Now, why I use it precisely?

Imagine you’ve some «Events» and some users you select when create the event, can «see» this event you create. So you «share» the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID’s corresponding to the users to share after modifying ($new). Wich ones you’ve to DELETE from DDBB, and wich ones do you’ve to INSERT?

If you do a simple difference or somehow, you get somethin’ like C=1,4.
You have no clue on wich one you’ve to insert or delete.

But on this way, you can know it, and that’s why:

I hope you find it useful, and I encourage PHP «makers», to add in a not distant future, somethin’ like this one natively, because I’m shure that I’m not the first one needing something like this.

Источник

array_unique

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

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

Описание

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

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

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

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

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

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

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

Примеры

Пример #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 ++;

Источник

Вложенные массивы — PHP: Массивы

Значением массива может быть всё, что угодно, в том числе массив. В этом случае синтаксис может выглядеть немного необычно, поэтому разберём его отдельным уроком. Создать массив в массиве можно так:

Каждый элемент, являющийся массивом, рассматривается как единое целое, что видно по размеру второго массива. Вложенность никак не ограничивается. Можно создавать массив массивов массивов и т. д.

Обращение ко вложенным массивам выглядит уже немного необычно, хотя и логично:

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

Изменение и добавление массивов в массив:

Вложенные массивы можно изменять напрямую, просто обратившись к нужному элементу:

То же самое касается и добавления нового элемента:

Для чего вообще могут понадобиться вложенные массивы? Таких примеров довольно много, начиная от математических концепций, например, матриц, заканчивая представлением игровых полей. Помните игру крестики-нолики? Это как раз тот самый случай.

Разберём для примера такую задачку. Дано игровое поле для крестиков-ноликов. Нужно написать функцию, которая проверяет, есть ли на этом поле хотя бы один крестик или нолик, в зависимости от того, что попросят проверить.

Теперь реализуем функцию, которая выполняет проверку:

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно.

Наши выпускники работают в компаниях:

С нуля до разработчика. Возвращаем деньги, если не удалось найти работу.

Источник

Убрать вложенность массива php

Reg.ru: домены и хостинг

Крупнейший регистратор и хостинг-провайдер в России.

Более 2 миллионов доменных имен на обслуживании.

Продвижение, почта для домена, решения для бизнеса.

Более 700 тыс. клиентов по всему миру уже сделали свой выбор.

Бесплатный Курс «Практика HTML5 и CSS3»

Освойте бесплатно пошаговый видеокурс

по основам адаптивной верстки

на HTML5 и CSS3 с полного нуля.

Фреймворк Bootstrap: быстрая адаптивная вёрстка

Пошаговый видеокурс по основам адаптивной верстки в фреймворке Bootstrap.

Научитесь верстать просто, быстро и качественно, используя мощный и практичный инструмент.

Верстайте на заказ и получайте деньги.

Что нужно знать для создания PHP-сайтов?

Ответ здесь. Только самое важное и полезное для начинающего веб-разработчика.

Узнайте, как создавать качественные сайты на PHP всего за 2 часа и 27 минут!

Создайте свой сайт за 3 часа и 30 минут.

После просмотра данного видеокурса у Вас на компьютере будет готовый к использованию сайт, который Вы сделали сами.

Вам останется лишь наполнить его нужной информацией и изменить дизайн (по желанию).

Изучите основы HTML и CSS менее чем за 4 часа.

После просмотра данного видеокурса Вы перестанете с ужасом смотреть на HTML-код и будете понимать, как он работает.

Вы сможете создать свои первые HTML-страницы и придать им нужный вид с помощью CSS.

Бесплатный курс «Сайт на WordPress»

Хотите освоить CMS WordPress?

Получите уроки по дизайну и верстке сайта на WordPress.

Научитесь работать с темами и нарезать макет.

Бесплатный видеокурс по рисованию дизайна сайта, его верстке и установке на CMS WordPress!

Хотите изучить JavaScript, но не знаете, как подступиться?

После прохождения видеокурса Вы освоите базовые моменты работы с JavaScript.

Развеются мифы о сложности работы с этим языком, и Вы будете готовы изучать JavaScript на более серьезном уровне.

*Наведите курсор мыши для приостановки прокрутки.

PHP: Удаление элементов массива

Перед нами стоит тривиальная с виду задача: удалить элемент массива. Или несколько элементов.

Однако, при всей ее простоте, в ней есть варианты, которые не совсем очевидны, и о которых стоит знать, если вы хотите продвинуться в PHP чуть дальше, чем «Hello, world!»:)

Начнем с самой базы: чтобы удалить один элемент, нужно воспользоваться функцией unset():

Здесь все просто и понятно.

Дальше. Для удаления нескольких несмежных элементов также используется функция unset(), просто мы передаем ей несколько параметров:

Следующий логичный вопрос: как удалить несколько элементов, которые следуют друг за другом (т.е. смежных)? Чтобы удалить несколько смежных элементов, воспользуйтесь функцией array_splice():

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

Важно понимать, что функция unset() удаляет элемент, в то время как присвоение элементу » не удаляет его, но означает что его значение становится равным пустой строке.

Если вы работаете с числами, вероятно, лучше будет связать с таким ключом значение 0.

Скажем, если компания прекратила производство деталей модели HBL-568, то в массив деталей можно внести изменение:

Если же детали HBL-568 нет на складе лишь временно и ожидается ее поступление с завода, то лучше поступать иначе:

Следующий момент, который нужно понимать, заключается в том, что при вызове функции unset() для элемента массива, PHP корректирует массив так, чтобы цикл по-прежнему работал правильно.

Иными словами, массив не сжимается для заполнения образовавшихся «дыр». По сути, это означает, что все массивы являются ассоциативными, даже если на первый взгляд кажутся числовыми. Давайте посмотрим на понятные примеры для иллюстрации этого поведения:

Чтобы перейти к плотно заполненному числовому массиву, воспользуйтесь функцией array_values():

Также функция array_splice() автоматически переиндексирует массивы для устранения «дыр»:

Где может пригодиться такая возможность?

Допустим, вы работаете с массивом как с очередью и хотите из этой очереди удалить элементы, не теряя при этом возможности произвольного доступа, когда вы могли бы случайно попасть в одну из образовавшихся «дыр».

Ну и, наконец, для безопасного удаления первого или последнего элемента из массива используются функции array_shift() и array_pop() соответственно.

С ними все очень просто:

В результате выполнения кода выше мы получим такой вывод:

Для удаления последнего элемента воспользуемся функцией array_pop():

На выходе получим следующую распечатку массива:

Понравился материал и хотите отблагодарить?
Просто поделитесь с друзьями и коллегами!

Источник

array_push

(PHP 4, PHP 5, PHP 7, PHP 8)

array_push — Добавляет один или несколько элементов в конец массива

Описание

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

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

Возвращает новое количество элементов в массиве.

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

ВерсияОписание
7.3.0Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра.

Примеры

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

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

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

User Contributed Notes 35 notes

If you’re going to use array_push() to insert a «$key» => «$value» pair into an array, it can be done using the following:

It is not necessary to use array_push.

Hope this helps someone.

Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do.

. but this is actually not true. Unlike array_push and even.

. Rodrigo’s suggestion is NOT guaranteed to append the new element to the END of the array. For instance.

$data[‘one’] = 1;
$data[‘two’] = 2;
$data[‘three’] = 3;
$data[‘four’] = 4;

. might very well result in an array that looks like this.

[ «four» => 4, «one» => 1, «three» => 3, «two» => 2 ]

I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won’t matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.

If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead.

$data[‘one’] = 1;
$data += [ «two» => 2 ];
$data += [ «three» => 3 ];
$data += [ «four» => 4 ];

You can also, of course, append more than one element at once.

$data[‘one’] = 1;
$data += [ «two» => 2, «three» => 3 ];
$data += [ «four» => 4 ];

. which will result in an array that looks like this.

[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]

This is how I add all the elements from one array to another:

If you’re adding multiple values to an array in a loop, it’s faster to use array_push than repeated [] = statements that I see all the time:

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

Adding 100k elements to array with array_push

Adding 100k elements to array with [] 10 per iteration

Adding 100k elements to array with array_push 10 per iteration

?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => a
[1] => b
[2] => c
)
)

There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output «d,e,f», not «a,b,c».

Need a real one-liner for adding an element onto a new array name?

Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There’s another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn’t check if a variable is an array first as array_push does. If array_push finds that a variable isn’t an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.

If you want to preserve the keys in the array, use the following:

elegant php array combinations algorithm

A common operation when pushing a value onto a stack is to address the value at the top of the stack.

This can be done easily using the ‘end’ function:

A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

Add elements to an array before or after a specific index or key:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *