Merging two multidimensional arrays on specific key

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

Let\'s say I have following arrays:

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


        
7条回答
  •  甜味超标
    2020-11-28 13:45

    As long as both arrays always have every id in them, what about sorting the two arrays by that 'id' field, then letting php do the merge?

    function cmp($a, $b) {
      return ((int) $a['id'] < (int) $b['id']) ? -1 : 1;
    }
    
    usort($array1, 'cmp');
    usort($array2, 'cmp');
    
    $result = array_merge($array1, $array2);
    

    Have not tested the code, but it demonstrates the idea.

提交回复
热议问题