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

PHP多维数组循环生成productCard卡片 单数组项渲染多张卡片问题排查

问题原因
  • 循环逻辑错误:你在遍历$pages单条子项的内层foreach中写入了卡片生成代码,每遍历子项的一个键值对就会生成一张新卡片,所以一个子数组的3个键(icon/subheader/url)会生成3张卡片,和你的预期不符。
  • 字段取值逻辑错误:你没有主动取出子项中subheader、url两个对应字段的值放到DOM的对应位置,而是直接输出遍历的$value,导致卡片内容错位。
修正后的代码

更简洁的foreach写法:

<?php
// 直接遍历$pages数组的每一个子项即可,不需要额外嵌套循环
foreach ($pages as $page) { ?>
    <div class="productCard">
        <div class="productCard__header">
            <!-- url here-->
            <?php echo $page['url']; ?>
        </div>
        <div class="productCard__body">
            <!--subheader here -->
            <?php echo $page['subheader']; ?>
        </div>
    </div>
<?php } ?>

如果要保留原有的for循环写法,直接删除内层foreach,通过索引取子项对应字段即可:

<?php
  $keys = array_keys($pages);
  for($i = 0; $i < count($pages); $i++) {
    // 直接取当前子项
    $currentPage = $pages[$keys[$i]];
?>
      <div class="productCard">
        <div class="productCard__header">
          <!-- url here-->
          <?php echo $currentPage['url']; ?>
        </div>
        <div class="productCard__body">
          <!--subheader here -->
          <?php echo $currentPage['subheader']; ?>
        </div>
      </div>
<?php } ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:15:03