PHP merge two arrays on the same key AND value

后端 未结 5 1300
误落风尘
误落风尘 2021-01-13 10:27

I have two arrays. And I want to merge them on the same key AND value. If they have the same ur_user_id then they are merged. array2 only provides

5条回答
  •  一生所求
    2021-01-13 10:43

    Try out this code, It might help you, it's short and without traversing loops:

        usort($array2,function($a,$b){
            return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
        });
        $array3 = array_replace_recursive($array1, $array2);
    
        $result = array_uintersect($array3,$array1,function($a,$b){
            return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
        });
        print_r($result);
    

    Output

    Array
    (
        [0] => Array
            (
                [ur_user_id] => 1
                [ur_fname] => PerA
                [ur_lname] => SonA
                [ur_code] => AA
                [ur_user_role] => testA
            )
    
        [1] => Array
            (
                [ur_user_id] => 2
                [ur_fname] => PerB
                [ur_lname] => SonB
                [ur_code] => BB
                [ur_user_role] => testB
            )
    
        [2] => Array
            (
                [ur_user_id] => 3
                [ur_fname] => PerC
                [ur_lname] => SonC
                [ur_code] => CC
                [ur_user_role] => testC
            )
    
    )
    

    And Here is Demo

提交回复
热议问题