PHP如何优雅将大括号格式日程字符串转换为多维数组
需求说明
将嵌套大括号包裹的日程字符串转换为二维数组,示例效果如下:
convert("{{09:00,10:00},{18:00,19:00}}") // 返回 [['09:00','10:00'],['18:00','19:00']]
最优优雅方案:JSON转换法
你给出的格式本质是把JSON数组的方括号替换为了大括号,直接替换括号后用json_decode解析即可,仅需1行核心逻辑,简洁易读:
function convert($schedules) { return json_decode(str_replace(['{', '}'], ['[', ']'], $schedules), true); }
备选适配方案:正则匹配法
如果你的输入可能存在其他不规则字符,可以用正则直接提取所有时间片段再分组,适配性更强:
function convert($schedules) { // 匹配所有HH:MM格式的时间串 preg_match_all('/\d{2}:\d{2}/', $schedules, $matches); // 每2个时间为一组拼装成二维数组 return array_chunk($matches[0], 2); }
原代码问题修正
你贴出的原有实现存在两个运行级错误:
- 入参命名为
$shedules,但第一行处理调用了未定义的变量$horaires - 末尾return语句缺少分号
修正后的原逻辑版本如下:
function convert($schedules) { $schedules = explode('},{', $schedules); $schedules = array_map(function ($schedule) { return explode(',', str_replace(['{', '}'], '', $schedule)); }, $schedules); return $schedules; }
内容的提问来源于stack exchange,提问作者Gautier
相关产品推荐
相关产品推荐

