简体   繁体   中英

Merge php array with dynamic key

If I query out the array like this form:

$arr1:

0 => 
      'id' => 1,
      'name' => 'a'
1 => 
     'id' => 2,
     'name' => 'b'
2 => 
     'id' => 3,
     'name' => 'c'
3 => 
     'id' => 4,
     'name' => 'd'
$arr2:

0 => 
      'id' => 1,
      'parent' => '1a'
1 => 
     'id' => 2,
     'parent' => '2b'
2 => 
     'id' => 3,
     'parent' => '3c'
3 => 
     'id' => 4,
     'parent' => '4d'

When I need to merge these two I can done it using foreach loop .

The problem comes to when the $arr1 is dynamic data ( need to use for pagination ), i can't merge well using array_merge due to $arr2 is fixed data.

example: first time:

$arr1:
0 => 
      'id' => 1,
      'name' => 'a'
1 => 
     'id' => 2,
     'name' => 'b'
$arr2:

0 => 
      'id' => 1,
      'parent' => '1a'
1 => 
     'id' => 2,
     'parent' => '2b'
2 => 
     'id' => 3,
     'parent' => '3c'
3 => 
     'id' => 4,
     'parent' => '4d'

second time:

$arr1:
0 => 
      'id' => 3,
      'name' => 'c'
1 => 
     'id' => 4,
     'name' => 'd'
$arr2:

0 => 
      'id' => 1,
      'parent' => '1a'
1 => 
     'id' => 2,
     'parent' => '2b'
2 => 
     'id' => 3,
     'parent' => '3c'
3 => 
     'id' => 4,
     'parent' => '4d'

I had try using foreach loop

foreach($arr1 as $k => $value){
  $group[$k]['parent'] = $arr2[$k]['parent'];
  $group[$k]['name'] = $value['name'];
  $group[$k]['id'] = $value['id'];
}

It comes to the parent value does not change as $key is fixed.

The expected output should all the element in 1 array :

0 => 
      'id' => 1,
      'parent' => '1a'
      'name'='a'
1 => 
     'id' => 2,
     'parent' => '2b'
     'name'='b'

I think this is what you need...

The easiest way to do this is to re-index the second array with the ID as the key. I use array_column() to do this. Then use the id from $arr1 to access the parent value from the newly indexed array...

$parent = array_column($arr2, 'parent', 'id');
$group = [];
foreach($arr1 as $k => $value){
    $group[$k]['parent'] = $parent[$value['id']];
    $group[$k]['name'] = $value['name'];
    $group[$k]['id'] = $value['id'];
}

In case $arr2 has more information, just use null as the second parameter to array_column() . Then you need to add the column name when you access that array...

$parent = array_column($arr2, null, 'id');
$group = [];
foreach($arr1 as $k => $value){
    $group[$k]['parent'] = $parent[$value['id']]['parent'];
    $group[$k]['name'] = $value['name'];
    $group[$k]['id'] = $value['id'];
}

Try this:

foreach($arr1 as $k=>$v) {
    $arr1[$k]['parent'] =  $arr2[$k]['parent'];
}


print_r( $arr1 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM