TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

PHP数组foreach循环嵌套优化

2021-03-22
/
0 评论
/
299 阅读
/
正在检测是否收录...
03/22

2个多维数组,要把两个数组的其中几个字段去合并成一个新的数组,或者把其中一个数组的字段加到另外一个数组中

//源数组
$array1 = (
    'detail' => array(
        [0] => array(
            'name' : 'test',
            'id' : 01
        ),
        [1] => array(
            'name' : 'test2',
            'id' : 02
        )
    )
);

$array2 = (
    'detail' => array(
        [0] => array(
            'id' : 01,
            'age' : 11,
        ),
        [1] => array(
            'id' : 02,
            'age' : 22,
        )
    )
);
//目标数组
$data = (
    'detail' => array(
        [0] => array(
            'name' : 'test',
            'id' : 01,
            'age' : 11,
        ),
        [1] => array(
            'name' : 'test2',
            'id' : 02,
            'age' : 22,
        )
    )
);

优化前的代码:

foreach ($array1['detail'] as $key=>&$val){
    foreach ($array2['detail'] as $k=>&$v){
        if ($array1['detail'][$val]['id']=$array2['detail'][$v]['id']){
            $array1['detail']['age'] = $array2['detail']['age'];
        }
    }
}

优化后代码:用索引

//先定义一个新的数组用于接收索引值
$newArr = array();
foreach ($array2['detail'] as $key=>$val){
    $newArr[$val['id']] = $val;
}
foreach ($array1['detail'] as $k=>&$v){
    if(isset($newArr[$v['id']])){
        $v['age'] = $newArr[$v['id']]['age'];
    }
}
unset($newArr);
经验PHPforeach嵌套优化
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwll.cn/archives/5036/(转载时请注明本文出处及文章链接)

评论 (0)