Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP merge arrays by value

Tags:

arrays

merge

php

I know this is quite easily accomplished with a foreach, then a while->list, etc procedure, (I have already accomplished it), however I sense that my code is a bit dirty and it doesn't look like the best solution... I'm looking to use native PHP array functions to do the following:

I have two arrays that look like this:

[0] (Array)#2
  [rank] "579"
  [id] "1"
[1] (Array)#4
  [rank] "251"
  [id] "2"

[0] (Array)#2
  [size] "S"
  [status] "A"
  [id] "1"
[1] (Array)#15
  [size] "L"
  [status] "A"
  [id] "2"

And I need as a result something like the following:

[0] (Array)#2
  [size] "S"
  [status] "A"
  [id] "1"
  [rank] "579"

[1] (Array)#2
  [size] "L"
  [status] "A"
  [id] "2"
  [rank] "251"

Is there a way to be able to merge two arrays with the id value (or ay other) without going into a endless set of foreachs?

like image 417
Osvaldo Mercado Avatar asked Nov 01 '11 22:11

Osvaldo Mercado


People also ask

How do you combine values in an array?

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.

What is the difference between array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() 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.

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.

What is the best method to merge two PHP objects?

Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.


1 Answers

Use array_merge_recursive()

$array = array_merge_recursive($array1, $array2);

or make your own function (it may be faster)

function my_array_merge(&$array1, &$array2) {
    $result = Array();
    foreach($array1 as $key => &$value) {
        $result[$key] = array_merge($value, $array2[$key]);
    }
    return $result;
}
$array = my_array_merge($array1, array2);
print_r($array);
like image 58
Peter Avatar answered Oct 12 '22 02:10

Peter