最新消息: 新版网站上线了!!!

2个二维数组合并(合并结果 键存在的赋值,不存在赋值为0)

数组1:数组变量为$userinfo
Array
(
[0] => Array
(
[author_id] => 1
[name] => 张三
)
[1] => Array
(
[author_id] => 947
[name] => 李四
)
[2] => Array
(
[author_id] => 950
[name] => 王麻子
)
)
数组2:数组变量$plan_num
Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
)
[5] => Array
(
)
[6] => Array
(
)
[7] => Array
(
)
[8] => Array
(
)
[9] => Array
(
)
[10] => Array
(
)
[11] => Array
(
)
[12] => Array
(
)
[13] => Array
(
)
[14] => Array
(
)
[15] => Array
(
)
[16] => Array
(
)
[17] => Array
(
[1] => Array
(
[num] => 1
[author_id] => 1
)
)
[18] => Array
(
)
[19] => Array
(
)
[20] => Array
(
[950] => Array
(
[num] => 1
[author_id] => 950
)
[1] => Array
(
[num] => 1
[author_id] => 1
)
)
[21] => Array
(
[1] => Array
(
[num] => 2
[author_id] => 1
)
)
)
希望合并的结果:
Array
(
[0] => Array
(
[author_id] => 1
[name] => 张三
[data] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 1
[18] => 0
[19] => 0
[20] => 1
[21] => 2
)
)
[1] => Array
(
[author_id] => 947
[name] => 李四
[data] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
[19] => 0
[20] => 0
[21] => 0
)
)
[2] => Array
(
[author_id] => 950
[name] => 王麻子
[data] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
[19] => 0
[20] => 1
[21] => 0
)
)
)
代码:
foreach($userinfo as $key=>$value){
    foreach($plan_num as $k=>$value){
        if(empty($plan_num[$k])){
            $userinfo[$key]['data'][$k] = 0;
        }else{
            foreach($value as $k_num=>$v_num){
                if($userinfo[$key][author_id] == $k_num){
                    $userinfo[$key]['data'][$k] = $v_num['num'];
                }elseif(!array_key_exists($userinfo[$key][author_id],$value)){
                    $userinfo[$key]['data'][$k] = 0;
                }
            }
        }
    }
}
print_r($userinfo);


转载请注明:谷谷点程序 » 2个二维数组合并(合并结果 键存在的赋值,不存在赋值为0)