普通网友 2012-01-13 06:00
浏览 48
已采纳

php代码改进重构

Hi staskoverflow community.

How can i improve next structure of PHP 5 code. A list of models $months (more than 12) $month->days (more than 31)

$day->clients a list of clients $day->someActions a list of actions for $clients

i need to invoke every $action for every $client. So my construction is:

<?php
foreach($monthes as $month) {
    foreach($month->days as $day) {
        foreach($day->clients as $client) {
            foreach($day->actions as $action) {
                $action->run($client);
            }
        }
    }
} ?>

So there are four foreach loops, can i improve this code ?

  • 写回答

1条回答 默认 最新

  • duanluwei9374 2012-01-13 09:11
    关注

    Why do you want to move out of nested loops? the code you have is very clear to understand and if your objective is to optimize the performance of this method, then the approach I would go with would be:

    1. I will first try to reduce the number of iterations. you can do this by asking questions to yourself like how many months data do I actually want to display on the go?
    2. Similar questions can be asked about days and clients
    3. do you have a break condition? What i mean by this is,

      $result = $action->run($client); if("break_condition" == $result){ break; }

    this should considerably reduce the number of iterations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题