PHP merge two arrays on the same key AND value

后端 未结 5 1425
误落风尘
误落风尘 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:45

    Try this three line code in foreach loop like this :

    $array1 =    
        array(
            array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'),
            array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'),
            array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'),
        );
    $array2 = 
        array(
            array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'),
            array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'),
            array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'),
            array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'),
            array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'),
            array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'),
        );
    
    $newArray =array(); 
    
    foreach($array1 as $key => $val)
    {
        $ids = array_map(function ($ar) {return $ar['ur_user_id'];}, $array2); //get the all the user ids from array 2
        $k = array_search($val['ur_user_id'],$ids); // find the key of user id in ids array
        $newArray[] = array_merge($array1[$key],$array2[$k]); /// merge the first array key with second
    }   
    
    echo "
    "; print_r($newArray);
    

    This will give you :

    (
        [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
            )
    
    )
    

    LIVE DEMO

提交回复
热议问题