function to simulate left join on array not working properly in PHP

后端 未结 1 379
独厮守ぢ
独厮守ぢ 2021-01-23 13:35

I have two arrays like this :

$left = [
    [\'UserID\' => 6835406],
    [\'UserID\' => 8418097],
];

$right = [
    [\'Amount\' => 0.00, \'UserID\' =&g         


        
相关标签:
1条回答
  • 2021-01-23 13:53

    I don't know why you did so long code, do like below:

    $finalArray = array();
    foreach($left as $lft){
        foreach($right as $rgt){
            if($lft['UserID']  == $rgt['UserID']){
               $finalArray[$lft['UserID']]['UserID'] = $lft['UserID'];
               $finalArray[$lft['UserID']]['Amount'] = (isset($rgt['Amount']) ? $rgt['Amount'] : NULL);
               break;
            }else{
                $finalArray[$lft['UserID']]['UserID'] = $lft['UserID'];
                $finalArray[$lft['UserID']]['Amount'] =  NULL;
            }
        }
    }
    $finalArray = array_values($finalArray);
    
    var_dump($finalArray);
    

    Output:-https://3v4l.org/TCnBb

    You can go for functional approach too:https://3v4l.org/aLWij

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