【发布时间】:2019-12-01 13:57:37
【问题描述】:
在我的应用程序中,我复制了包含 foreach 的代码。我有一个 foreach,我只将值从 $schedules 存储到新的 array。然后我用另一个 foreach 来检查这个数组是否在新的 $array 中。
我这里有一个数组$schedules:
$schedules = [
[
"time_start" => "08:00:00",
"time_end" => "12:00:00",
"in_threshold" => 50,
"out_threshold" => 15
],
[
"time_start" => "13:00:00",
"time_end" => "17:00:00",
"in_threshold" => 30,
"out_threshold" => 45
]
];
所以我有这段代码 sn-p 使用 forloop 存储到新数组:
foreach($schedules as $schedule){
// Set time_start and time_end to array
$sched_starts[] = ( $schedule[ 'time_start' ] );
$sched_ends[] = ( $schedule[ 'time_end' ] );
// Set time_start and time_end with threshold to array
$time_start[] = date( "H:i:s",
strtotime('+'. $schedule[ 'in_threshold' ] .' minutes',
strtotime ( $schedule[ 'time_start' ]
)));
$time_end[] = date( "H:i:s",
strtotime('+'. $schedule[ 'out_threshold' ] .' minutes',
strtotime( $schedule[ 'time_end' ]
)));
}
我想在不使用循环的情况下获取$sched_starts、$sched_ends、$time_start 和$time_end,以避免重复循环。所以我使用了array_column 和array_walk_recursive 函数,但我无法获得 $time_start 和 $time_end 然后我意识到这两个函数只能在 $一次安排。
是否可以不使用loop 获取$time_start 和$time_end?
【问题讨论】:
-
没有兴趣使用
array_walk_recursive(或array_map)来避免for循环,因为它在底层使用循环。这里的问题是要知道您的 2 个循环执行哪些任务。如果第二个需要第一个的完整结果,则需要 2 个单独的循环。它没有错。如果任务是独立的,请在同一循环中执行 2。这就是为什么我们需要完整的代码来给你建议。另一件事,如果你的 2 个循环中没有性能问题,你不应该真的打扰。 -
@Rubics 我的帖子是否达到了避免循环的目标?有帮助还是不是你的意思?