Merging two multidimensional arrays on specific key

前端 未结 7 2244
南方客
南方客 2020-11-28 13:13

Let\'s say I have following arrays:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
            


        
7条回答
  •  我在风中等你
    2020-11-28 13:23

    You code works fine. Your expectations are simply incorrect. For example in one array 4th element id holds 1 but in another array, 4th element id is 5, so your "merge these arrays on the same id" makes no sense as by merging 4th elements into one you also merge their children, and since id is used in both arrays, once value HAVE TO be gone as there cannot be two equal keys in array.

    EDIT

    you have to merge manually as PHP functions merge based on keys while you want to merge based on content:

    $result = array();
    foreach( $arrayA as $keyA => $valA ) {
      foreach( $arrayB as $keyB => $valB ) {
         if( $valA['id'] == $valB['id'] ) {
           $result[$keyA] = $valA + $valB;
    
           // or if you do not care output keys, just
           // $result[] = $valA + $valB;
         }
      }
    }
    

提交回复
热议问题