PHP 数组array foreach循环嵌套foreach优化

前言:前端时间工作中经常碰到拿到2组或以上数据需要重新组装成新的数组的需求,最基本的办法就是用foreach循环嵌套拿数据去处理

先上需求,拿到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);

你可能感兴趣的:(php,PHP,array,foreach)