Array merge on key of two associative arrays in php?

后端 未结 1 1218
执念已碎
执念已碎 2020-12-30 18:13

How can I merge these two array together?

Array
(
[0] => Array
    (
        [id] => 5
        [cnt] => 14
    )

[1] => Array
    (
        [id]         


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 19:06

    $output = array();
    
    $arrayAB = array_merge($arrayA, $arrayB);
    foreach ( $arrayAB as $value ) {
      $id = $value['id'];
      if ( !isset($output[$id]) ) {
        $output[$id] = array();
      }
      $output[$id] = array_merge($output[$id], $value);
    }
    
    var_dump($output);
    

    Optionally if you want to reset output's keys, just do:

    $output = array_values($output);
    

    0 讨论(0)
提交回复
热议问题