优化后的代码如下:

foreach ($boxItemList as $boxItem) {
    if (empty($boxItem->item_id)) {
        continue;
    }
    $rareColor = $boxItem->rare_color;
    if (isset($rareColorList[$rareColor])) {
        $rareColorList[$rareColor]['rate'] = bcadd($rareColorList[$rareColor]['rate'], $boxItem->probability, 2);
    } else {
        $rareColorList[$rareColor] = [
            'color' => $rareColor,
            'rate' => round($boxItem->probability, 2),
        ];
    }
}

主要的优化点是将 $boxItem->rare_color 的值存储到一个变量 $rareColor 中,避免在 if 语句中多次访问 $boxItem->rare_color,提高代码的执行效率。

PHP代码优化:提高循环效率的技巧

原文地址: https://www.cveoy.top/t/topic/njbb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录