php merge assoc array
array_merge
(PHP 4, PHP 5, PHP 7, PHP 8)
array_merge — Сливает один или большее количество массивов
Описание
Сливает элементы одного или большего количества массивов таким образом, что значения одного массива присоединяются к концу предыдущего. Результатом работы функции является новый массив.
Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.
В результирующем массиве значения исходного массива с числовыми ключами будут перенумерованы в возрастающем порядке, начиная с нуля.
Список параметров
Возвращаемые значения
Возвращает результирующий массив. Если вызывается без аргументов, возвращает пустой массив ( array ).
Список изменений
Версия | Описание |
---|---|
7.4.0 | Функция теперь может быть вызвана без каких-либо параметров. Ранее требовался хотя бы один параметр. |
Примеры
Пример #1 Пример использования array_merge()
Результат выполнения данного примера:
Пример #2 Простой пример использования array_merge()
Помните, что числовые ключи будут перенумерованы!
Если вы хотите дополнить первый массив элементами второго без перезаписи элементов первого массива и без переиндексации, используйте оператор объединения массивов + :
Ключи из первого массива будут сохранены. Если ключ массива существует в обоих массивах, то будет использован элемент из первого массива, а соответствующий элемент из второго массива будет проигнорирован.
Пример #3 Пример использования array_merge() с не массивами
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 2 notes
In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that.
[ 0 ] = «zero» ;
$array1 [ 1 ] = «one» ;
$array2 [ 1 ] = «one» ;
$array2 [ 2 ] = «two» ;
$array2 [ 3 ] = «three» ;
//This will result in::
?>
Note the implicit «array_unique» that gets applied as well. In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.
PHP combine two associative arrays into one array
I need a new array combining all together, i.e. it would be
What is the best way to do this?
Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn’t sure if that was best way to do this. Also, how would you unit test this?
7 Answers 7
array_merge() is more efficient but there are a couple of options:
‘; // Results: array(4) < ["id1"]=>string(6) «value1» [«id2»]=> string(6) «value2» [«id3»]=> string(6) «value3» [«id4»]=> string(6) «value4» > array(4) < ["id1"]=>string(6) «value1» [«id2»]=> string(6) «value2» [«id3»]=> string(6) «value3» [«id4»]=> string(6) «value4» >
I use a wrapper around array_merge to deal with SeanWM’s comment about null arrays; I also sometimes want to get rid of duplicates. I’m also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
If it is numeric but not sequential associative array, you need to use array_replace
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn’t have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge() +1 to him.
Maybe this will help someone else out.
And I needed to merge them keeping the same structure like this:
PHP array_merge() Function
Example
Merge two arrays into one array:
Definition and Usage
The array_merge() function merges one or more arrays into one array.
Tip: You can assign one array to the function, or as many as you like.
Note: If two or more array elements have the same key, the last one overrides the others.
Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value (See example below).
Tip: The difference between this function and the array_merge_recursive() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.
Syntax
Parameter Values
Parameter | Description |
---|---|
array1 | Required. Specifies an array |
array2 | Optional. Specifies an array |
array3. | Optional. Specifies an array |
Technical Details
Return Value: | Returns the merged array |
---|---|
PHP Version: | 4+ |
Changelog: | As of PHP 5.0, this function only accept parameters of type array |
More Examples
Example
Merge two associative arrays into one array:
Example
Using only one array parameter with integer keys:
array_combine
array_combine — Создаёт новый массив, используя один массив в качестве ключей, а другой для его значений
Описание
Создаёт массив ( array ), используя значения массива keys в качестве ключей и значения массива values в качестве соответствующих значений.
Список параметров
Массив ключей. Некорректные значения для ключей будут преобразованы в строку ( string ).
Возвращаемые значения
Ошибки
Примеры
Пример #1 Простой пример использования array_combine()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 21 notes
If two keys are the same, the second one prevails.
But if you need to keep all values, you can use the function below:
Further to loreiorg’s script
in order to preserve duplicate keys when combining arrays.
I have modified the script to use a closure instead of create_function
Reason: see security issue flagged up in the documentation concerning create_function
// If they are not of same size, here is solution:
// Output
// Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
// [AR] => Arkansas )
?>
This will seem obvious to some, but if you need to preserve a duplicate key, being you have unique vars, you can switch the array_combine around, to where the vars are the keys, and this will output correctly.
This [default] formula auto-removes the duplicate keys.
This formula accomplishes the same thing, in the same order, but the duplicate «keys» (which are now vars) are kept.
I know, I’m a newbie, but perhaps someone else will need this eventually. I couldn’t find another solution anywhere.
I was looking for a function that could combine an array to multiple one, for my MySQL GROUP_CONCAT() query, so I made this function.
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.
Array
(
[0] => Array
(
[SMART Board] => serial to smart board1
[Projector] => serial to projector 1
[Speakers] => serial to speakers 1
[Splitter] => serials to splitter 1
)
[1] => Array
(
[SMART Board] => serials to smart board 2
[Projector] => serials to projector 2
[Speakers] => serials to speakers 2
[Splitter] => serials to splitter 2
)