codeigniter 在PHP中模拟数组左连接的函数无法正常工作

3okqufwl  于 2022-12-07  发布在  PHP
关注(0)|答案(2)|浏览(106)

我有两个这样的数组:

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

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

我将使用此函数对基于UserID字段的数组执行左连接:

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;
}

我这样调用函数:

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

输出如下:

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

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

)

但期望的输出应该是这样的:

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

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

    )

我的代码有什么问题?为什么它没有给予所需的输出。任何建议都是有帮助的。

yc0p9oo0

yc0p9oo01#

我不知道你为什么做了这么长的代码,做得像下面这样:

$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);

输出:-https://3v4l.org/TCnBb
您也可以采用功能性方法:https://3v4l.org/aLWij

kdfy810k

kdfy810k2#

与Anant在嵌套循环中的无情条件相比,使用查找数组和单个循环合并右侧数组数据和左侧数组数据更高效、更简洁。
代码:(Demo

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

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

$lookup = array_column($right, null, 'UserID');
foreach ($left as &$row) {
    $row += $lookup[$row['UserID']] ?? [];
}

var_export($left);

输出量:

array (
  0 => 
  array (
    'UserID' => 6835406,
    'Amount' => 0.0,
  ),
  1 => 
  array (
    'UserID' => 8418097,
    'Amount' => 0.0,
  ),
  2 => 
  array (
    'UserID' => 6666666,
  ),
)

相关问题