John the horn
John the horn

Reputation: 131

Merge/combine 2 arrays with a common key

I have 2 arrays

$firstarray = [ ['name'='a', 'price'=1],['name'='b', 'price'=2],... ]
$secondarray = [ ['name'='b', 'year'=1999],['name'='a', 'year'=2000],... ]

how do I combine the together based on the name to result

$resultingarry = [ ['name'='a', 'year'=2000, price'=1],....] 

I tried array_merge_recursive and array_merge_recursive_distinct, but these are dependent on the key so the order will always be off.

Thanks in advance

Upvotes: 0

Views: 125

Answers (1)

ArSeN
ArSeN

Reputation: 5258

I do not know of a PHP function (nor a laravel one) that can do this. It's pretty simple with some loops though:

$firstarray = [ ['name'=>'a', 'price'=>1],['name'=>'b', 'price'=>2],];
$secondarray = [ ['name'=>'b', 'year'=>1999],['name'=>'a', 'year'=>2000],];

$resultingarray = [];

foreach ($firstarray as $entry) {
    // find entry with same "name" in second array
    foreach ($secondarray as $secondentry) {
        if ($secondentry['name'] == $entry['name']) {
            $resultingarray[] = array_merge($entry, $secondentry);
            continue 2;
        }
    }
}

var_dump($resultingarray);

Results in:

array(2) {
  [0]=>
  array(3) {
    ["name"]=>
    string(1) "a"
    ["price"]=>
    int(1)
    ["year"]=>
    int(2000)
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(1) "b"
    ["price"]=>
    int(2)
    ["year"]=>
    int(1999)
  }
}

Note that this only merges the first "match" (entry from the second array with the same name value in the first one).

Upvotes: 1

Related Questions