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

PHP implode拼接列车经停站列表出现数据累加错误如何解决

错误原因

$names数组在整个班次循环过程中没有被重置,每次处理新班次的经停站时,都会把新站点追加到存储了之前所有班次站点的数组中,最终拼接出来的字符串自然会累加前面的内容。你单独输出$row_calls['callingPoint']时数据正确,也刚好验证了查询逻辑没问题,问题出在数组的持久化存储上。

修复方案

每次处理当前班次的经停站之前,先清空$names数组即可,同时可以把implode操作放到经停站循环结束后执行,减少不必要的重复拼接:

<section id="section">
<?php
  do {    ?>
    <div class="container">
    <div class="fixed1"><?php print date("H:i",strtotime($row_fids['ScheduleTime']));?></div>
    <div class="fixed2"><?php print $row_fids['Operator'];?></div>
    <div class="fixed3"><?php print $row_fids['Dest_location'];?></div>
    <div class="fixed4"><?php echo $row_fids['Platform'];?></div>
    <div class="fixed5"><?php print $row_fids['Estimated'];?></div>
   <?php
// 用当前班次的ServiceID查询对应经停站
   $query_calls = "SELECT DISTINCT callingPoint FROM UKRail_departboard_calling_points WHERE ServiceID = '".$row_fids['ServiceID']."'";
   $calls = mysqli_query($navex, $query_calls) or die(mysqli_error($navex));
   $row_calls = mysqli_fetch_assoc($calls);
   $totalRows_calls = mysqli_num_rows($calls);

   // 新增:每次查询前清空经停站数组,避免旧数据残留
   $names = [];
   do {
     $names[] = $row_calls['callingPoint']; // 生成经停站数组
   }while($row_calls = mysqli_fetch_array($calls));
   // 移到循环外执行拼接,仅执行一次即可
   $callingat = implode(', ', $names); // 用implode转成逗号分隔字符串
?>
    // 展示经停站
   <div class="callingatheader">Calling at: </div>
   <div class="callslist"><?php echo $callingat;?></div>
<?php    } while($row_fids = mysqli_fetch_assoc($fids));?>
</section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:45:01