避免循环嵌套

一个实现合并二维数组相同 key 的写法:
$arr1 = array(
    array('num'=>5,'period'=>3),
    array('num'=>10,'period'=>3),
    array('num'=>15,'period'=>9)
);

$arr2 = array();

foreach($arr1 as $k1 => $v1) {
    if(empty($arr2)) {
        $arr2[] = $v1;
    } else {
        foreach ($arr2 as &$v2) {
            if($v1['period'] == $v2['period']) {
                $v2['num'] += $v1['num'];   
            } else {
                $arr2[] = $v1;
            }
        }
    }
}

1.不必要的嵌套循环
2.变量命名不清晰
3.} 堆叠使得代码可读性极差

规范写法:

rr = array(
    array('num'=>5,'period'=>3),
    array('num'=>10,'period'=>3),
    array('num'=>15,'period'=>9)
);
$temp = array();
foreach($arr as $item) {
    list($n, $p) = array_values($item);
    $temp[$p] =  array_key_exists($p, $temp) ? $temp[$p]+$n : $n;
}

$arr = array();
foreach($temp as $p => $n)
    $arr[] = array('num'=>$n, 'period'=>$p);

print_r($arr);

1.拆开循环
2.利用 PHP 自带的数组函数简化了代码
3.代码可读性较强

你可能感兴趣的:(php)