php пересечение двух массивов
array_intersect
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_intersect — Вычисляет схождение массивов
Описание
Список параметров
Основной проверяемый массив
Массивы, с которыми идёт сравнение значений
Возвращаемые значения
Примеры
Пример #1 Пример использования array_intersect()
Результат выполнения данного примера:
Примечания
Смотрите также
User Contributed Notes 32 notes
A clearer example of the key preservation of this function:
?>
yields the following:
This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,
Array
(
[ 0 ] => Array
(
[ 0 ] => John Doe
[ 1 ] => PHP Book
)
[ 1 ] => Array
(
[ 0 ] => Jack Smith
[ 1 ] => Coke
)
Array
(
[ 0 ] => Array
(
[ 0 ] => John Doe
[ 1 ] => PHP Book
)
?>
showing us who bought the same thing today and yesterday =)
Using isset to achieve this, is many times faster:
array_intersect: 4.717
array_flip+isset: 0.056
Take care of value types while using array_intersect function as there is no option for strict type check as in in_array function.
$array1 = array(true,2);
$array2 = array(1, 2, 3, 4, 5, 6);
result is :
array(2) <
[0] => bool(true)
[1] => int(2)
>
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:
This function is able to sort an array based on another array that contains the order of occurrence. The values that are not present will be transferred into the end of the resultant.
Questa funzione permette di ordinare i valori di un array ($tosort) basandosi sui valori contenuti in un secondo array ($base), i valori non trovati verranno posizionati alla fine dell’ordinamento senza un’ordine specifico.
I used array_intersect in order to sort an array arbitrarly:
0 => ‘one’
1 => ‘four’
2 => ‘five’
3 => ‘height’
i hope this can help.
But it is not needed! See below.
Extending the posting by Terry from 07-Feb-2006 04:42:
If you want to use this function with arrays which have sometimes the same value several times, it won’t be checked if they’re existing in the second array as much as in the first.
So I delete the value in the second array, if it’s found there:
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn’t find a good function for comparing values to keys. So I wrote this relatively straightforward one:
Array ( [first] => 2 [third] => 3 )
If you’re looking for a relatively easy way to strictly intersect keys and values recursively without array key reordering, here’s a simple recursive function:
I couldn’t get array_intersect to work with two arrays of identical objects, so I just did this:
Seems to work fine & reasonably quickly.
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you’re expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.
I bench-marked some uses of array_intersect and can’t believe how slow it is. This isn’t as elaborate, but handles most cases and is much faster:
?>
You can try this out with this:
Note that array_intersect() considers the type of the array elements when it compares them.
If array_intersect() doesn’t appear to be working, check your inputs using var_dump() to make sure you’re not trying to intersect an array of integers with an array of strings.
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.
If you wish to change this. I sugest that you do this.
It simply «ignores» empty arrays. Before loop use 1st array.
$b = array();
$b [] = 4 ;
$b [] = 5 ;
$b [] = 1 ;
$c = array();
$c [] = 1 ;
$c [] = 5 ;
$d = array();
array_intersect_assoc
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
array_intersect_assoc — Вычисляет схождение массивов с дополнительной проверкой индекса
Описание
Список параметров
Основной проверяемый массив.
Массивы, с которыми идёт сравнение.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_intersect_assoc()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 4 notes
1 =>
(
a => green
b => brown
c => yellow
e => yellow
)
2 =>
(
a => green
b => brown
c => blue
0 => red
)
3 =>
(
a => green
b => yellow
c => yellow
0 => red
)
$result_array will look like:
One of the ways to get intersection of two arrays is as follows:
To find the keys that are in 2 arrays, without caring of the values:
This is a function i needed, and it also returns the values of the first array
Remember, null values will be interpreted as, «key does not exist.» eg,
$a = [‘apples’ => 1, ‘oranges’ => 2, ‘turtles’ => null, ‘bananas’=>4];
$b = [‘apples’=>10, ‘turtles’ => 11, ‘eggs’=>12];
$c = array_intersect_assoc($b,$a);
[‘oranges’ => 10, ‘turtles’ => 11]
Something to keep in mind if using array_intersect_assoc to filter valid entries, eg in a mySQL insertion pre-processing or nerdy API that doesn’t like extra params.
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
array_diff_assoc
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
array_diff_assoc — Вычисляет расхождение массивов с дополнительной проверкой индекса
Описание
Список параметров
Массивы для сравнения
Возвращаемые значения
Примеры
Пример #1 Пример использования array_diff_assoc()
Результат выполнения данного примера:
Пример #2 Пример использования array_diff_assoc()
Результат выполнения данного примера:
Примечания
Замечание: Убедитесь, что передаёте аргументы в правильном порядке, когда сравниваете схожие массивы с большим количеством ключей. Новый массив должен быть первым.
Смотрите также
User Contributed Notes 18 notes
Works more like the original function:
an earlier post for recursive array_diff_assoc failed because isset returned false on an array element containing a null value. I updated the code so it compares null values too.
If you’re looking for a true array_diff_assoc, comparing arrays to determine the difference between two, finding missing values from both, you can use this along with array_merge.
print_r(array_diff_assoc($b,$a));
// returns
array
(
[d] => 4
)
print_r(array_merge(array_diff_assoc($a,$b),array_diff_assoc($b,$a)));
// returns
array
(
[c] => 3
[d] => 4
)
The following will recursively do an array_diff_assoc, which will calculate differences on a multi-dimensional level. This not display any notices if a key don’t exist and if error_reporting is set to E_ALL:
The direction of the arguments does actually make a difference:
To diff between n-dimensional array, juste use this :
To unset elements in an array if you know the keys but not the values, you can do:
array_diff_assoc can also be used to find the duplicates in an array
NOTE: the diff_array also removes all the duplicate values that match to the values in the second array:
// yields: array(«b»,»c») the duplicate «a» values are removed
?>
Recursive implementation accepting multiple n-level-arrays as parameters:
For recursive diff of multiple arrays, exending solution provided by Gosh.
Yet another recursive implementation, without if-else hell and with multiple parameters just like the original.
Как сделать пересечение массивов массивов
Я пытаюсь сделать функцию в php, которая пытается пересечь массив массивов. я нашел array_intersect($resultx,$resulty); но это работает только для таблиц с одним значением. В моем случае у меня есть такие массивы.
Чтобы возобновить свою проблему, я пытаюсь пересечь множество таблиц, подобных той, которую я упомянул. Так что любая идея
примеры tab1 [[1,2,3], [2,3,1]] tab2 [[1,2,3], [5,7,7] результат будет tab3 [[1,2,3]] тебе понятно?
Решение
@ KANDROID OS, пожалуйста, проверьте приведенный ниже пример для пересечения массивов.
Предположим, у вас есть два массива, как показано ниже:
Вы можете использовать array_uintersect () для использования пользовательской функции сравнения, например:
Таким образом, результат выше как ниже:
Другие решения
Вы можете сделать это рекурсивно так:
Вы должны быть осторожны, хотя, в примере, использующем обратный вызов, попытка использовать пересечение для значений ‘name’ и ‘id’ НЕ БУДЕТ возвращать парные значения, как вы могли ожидать. Нужно только найти одно из значений, поэтому, если вы попытаетесь найти «имя», которое соответствует другому «id», вы получите оба элемента обратно, даже если эта «комбинация» не существует. Он будет делать то же самое, даже если вы используете ключи в поиске следующим образом:
Я только что заметил эту проблему, поэтому я решил поднять ее. В зависимости от того, что вы пытаетесь сделать, вам может понадобиться какой-то рекурсивный аспект, как я уже показал.