How to add data from one array to another when key matches with nested foreach loops?

Viewed 14

I have 2 arrays of which I am wanting to add data from one to the other in the case where the id properties of both match.

$arr1 = [['id' => 123, 'name' => 'joe'], ['id' => 321, 'name' => 'bloggo']];
$arr2 = [['id'=> 123, 'job' => 'bin man'], ['id'=> 999, 'job' => 'salary man']];

foreach($arr1 as $nameArr) {
  foreach($arr2 as $jobArr) {
    if ($nameArr['id'] == $jobArr['id']) {
      $nameArr['job'] = $jobArr['job'];
    }
  }
}

echo json_encode($arr1);

This echoes the same as we see in $arr1.

I know I am missing something, I just can't wrap my head around what is missing.

1 Answers

You missing the use of a reference, so that the array will be changed:

$arr1 = [['id' => 123, 'name' => 'joe'], ['id' => 321, 'name' => 'bloggo']];
$arr2 = [['id'=> 123, 'job' => 'bin man'], ['id'=> 999, 'job' => 'salary man']];

foreach($arr1 as &$nameArr) {
#----------------^
  foreach($arr2 as $jobArr) {
    if ($nameArr['id'] == $jobArr['id']) {
      $nameArr['job'] = $jobArr['job'];
    }
  }
}

echo json_encode($arr1);

this works also without references when you act on the original array:

$arr1 = [['id' => 123, 'name' => 'joe'], ['id' => 321, 'name' => 'bloggo']];
$arr2 = [['id'=> 123, 'job' => 'bin man'], ['id'=> 999, 'job' => 'salary man']];

foreach($arr1 as $key => $nameArr) {
  foreach($arr2 as $jobArr) {
    if ($nameArr['id'] == $jobArr['id']) {
      #here
      $arr1[$key]['job'] = $jobArr['job'];
    }
  }
}

echo json_encode($arr1);

https://www.php.net/manual/en/control-structures.foreach.php

Related