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

如何从PHP生成的时间段列表中提取开始时间?

解决方案

要提取时间段中的开始时间,你可以通过字符串拆分或截取的方式处理每个$ts变量,以下是两种可行的修改方案:

方案1:使用explode()拆分字符串

利用explode()将时间段字符串按-分割成数组,取数组第一个元素即为开始时间:

<?php
    $timesolts = timeslots($duration, $cleanup, $start, $end);
    foreach ($timesolts as $ts) {
        // 拆分时间段,提取开始时间
        $startTime = explode('-', $ts)[0];
?>
        <button disabled type="button" class="btn btn-danger btn-sm" style="margin-bottom:5px; font-size: 12px;" data-timeslot="<?php echo $startTime; ?>" >
            <?php echo $startTime; ?>
        </button>
<?php } ?>

方案2:使用substr()固定截取

由于你的时间段格式是固定的HH:MM-HH:MM,开始时间恰好是前5个字符,直接截取即可:

<?php
    $timesolts = timeslots($duration, $cleanup, $start, $end);
    foreach ($timesolts as $ts) {
        // 截取前5个字符作为开始时间
        $startTime = substr($ts, 0, 5);
?>
        <button disabled type="button" class="btn btn-danger btn-sm" style="margin-bottom:5px; font-size: 12px;" data-timeslot="<?php echo $startTime; ?>" >
            <?php echo $startTime; ?>
        </button>
<?php } ?>

两种方案都能实现需求:按钮的显示文本和data-timeslot属性都会替换为时间段的开始时间(比如08:00、09:00)。如果后续时间段格式可能变化,优先选择方案1,兼容性更强;如果格式固定不变,方案2的性能略优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:27:13