Search code examples
phparrayscodeignitermultidimensional-arraycodeigniter-3

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


I have two arrays like this :

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

$right = [
    ['Amount' => 0.00, 'UserID' => 6835406],
    ['Amount' => 0.00, 'UserID' => 8418097]
];

I'm using this function to perform a left join on the arrays based on the UserID feild :

function left_join_array($left, $right, $left_join_on, $right_join_on = NULL){
    $final= array();

    if(empty($right_join_on))
        $right_join_on = $left_join_on;

    foreach($left AS $k => $v){
        $final[$k] = $v;
        foreach($right AS $kk => $vv){
            if($v[$left_join_on] == $vv[$right_join_on]){
                foreach($vv AS $key => $val)
                    $final[$k][$key] = $val;
            } else {
                foreach($vv AS $key => $val)
                    $final[$k][$key] = NULL;           
            }
        }
    }
   return $final;
}

I call the function like this :

$out = $this->left_join_array($left,$right,'UserID','UserID');
echo "<pre>";print_r($out);

and here is the output :

Array
(
    [0] => Array
        (
            [UserID] => 
            [Amount] => 
        )

    [1] => Array
        (
            [UserID] => 8418097
            [Amount] => 0.00
        )

)

but the desired output should have been like this :

 Array
    (
        [0] => Array
            (
                [UserID] => 6835406
                [Amount] => 0.00
            )

        [1] => Array
            (
                [UserID] => 8418097
                [Amount] => 0.00
            )

    )

What's wrong with my code? Why doesn't it give the desired output. Any suggestions would be helpful.


Solution

  • 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