You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于day_index生成工作日状态数组的PHP实现问题

问题分析与解决方案

原代码存在的问题

  • 嵌套循环的覆盖问题:内层循环遍历$working_hours_arr的每一个元素时,都会重复给$schedule[$day]赋值。哪怕当前day匹配到了某个工作日对象,后续不匹配的对象会再次覆盖working状态为false,最终所有项的working都变成false。
  • 数组赋值错误:代码中先给$schedule[$day]赋值['day_index' => $index],随后又直接赋值['working' => ...],这会完全替换掉之前的数组,导致最终的$schedule元素里只有working键,丢失了day_index。

修正后的实现

先把工作日的day_index提取到一个数组中,通过in_array快速判断当前day是否在工作日列表里,同时正确构建包含day_index和working的数组:

$working_hours_arr = '[{"day_index":"2","start_time":"10:00:00","end_time":"19:00:00","break":[]},{"day_index":"3","start_time":"11:00:00","end_time":"20:00:00","break":[]},{"day_index":"4","start_time":"10:00:00","end_time":"19:00:00","break":[]},{"day_index":"5","start_time":"11:00:00","end_time":"20:00:00","break":[]}]';

$days = [
    'Sunday' => 1,
    'Monday' => 2,
    'Tuesday' => 3,
    'Wednesday' => 4,
    'Thursday' => 5,
    'Friday' => 6,
    'Saturday' => 7,
];

// 提取所有工作日的day_index到数组,方便快速判断
$working_day_indices = array_map(function($item) {
    return (int)$item->day_index;
}, json_decode($working_hours_arr));

$schedule = [];
foreach ($days as $day => $index) {
    // 判断当前day的index是否在工作日列表中
    $is_working = in_array($index, $working_day_indices);
    // 正确构建包含两个键的数组
    $schedule[$day] = [
        'day_index' => $index,
        'working' => $is_working
    ];
}

var_dump($schedule);

代码说明

  1. 提取工作日索引:用array_map把解码后的$working_hours_arr中的每个对象的day_index转成整数后存入$working_day_indices,后续判断只需要一次数组查找,效率更高。
  2. 避免覆盖:外层循环遍历每个day时,只做一次判断,直接生成包含day_index和working的数组,不会被后续元素覆盖。
  3. 正确赋值数组:一次性构建包含两个键的关联数组,避免分开赋值导致的键丢失问题。

内容的提问来源于stack exchange,提问作者muser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:14:38