Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge PHP arrays?

Tags:

arrays

php

I have two arrays of animals (for example).

$array = array(
    array(
        'id' => 1,
        'name' => 'Cat',
    ),
    array(
        'id' => 2,
        'name' => 'Mouse',
    )
);

$array2 = array(
    array(
        'id' => 2,
        'age' => 321,
    ),
    array(
        'id' => 1,
        'age' => 123,
    )
);

How can I merge the two arrays into one by the ID?

like image 708
AnnanFay Avatar asked Aug 24 '08 16:08

AnnanFay


People also ask

How do I merge two arrays together?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

How do I combine two arrays from another array?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.

What is the use of array merge function in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.


1 Answers

@Andy

http://se.php.net/array_merge

That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now.

like image 181
Ross Avatar answered Oct 19 '22 00:10

Ross