函数模拟数组上的左连接在PHP中无法正常工作
作者:互联网
我有两个这样的数组:
$left = [
['UserID' => 6835406],
['UserID' => 8418097],
];
$right = [
['Amount' => 0.00, 'UserID' => 6835406],
['Amount' => 0.00, 'UserID' => 8418097]
];
我正在使用此函数基于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;
}
我这样调用该函数:
$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
)
)
我的代码有什么问题?
为什么不提供所需的输出.
任何的意见都将会有帮助.
解决方法:
我不知道您为什么要花这么长时间的代码,如下所示:
$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/aLWij
标签:codeigniter-3,php,arrays,multidimensional-array,codeigniter 来源: https://codeday.me/bug/20191014/1912118.html