首页 > 解决方案 > 基于多维数组生成标记

问题描述

我有以下内容multidimensional array

$pages = array(
  array(
    "icon" => "",
    "subheader" => "Insights",
    "url" => "/insights/",
  ),
  array(
    "icon" => "",
    "subheader" => "Statistics",
    "url" => "/statistics/",
  ),
);

我正在尝试遍历array并使用上述内容创建卡片。这是我循环的方式array

<?php
  $keys = array_keys($pages);
  for($i = 0; $i < count($pages); $i++) {
    foreach($pages[$keys[$i]] as $key => $value) { ?>

      <div class="productCard">
        <div class="productCard__header">
          <!-- url here-->
        </div>
        <div class="productCard__body">
          <!--subheader here -->
          <?php echo $value; ?>
        </div>
      </div>

    <?php }
  }
?>

上面的循环渲染出来(对于数组中的一项):

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Insights
  </div>
</div>

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    /insights/
  </div>
</div>

如您所见,它productCard为每个键生成一个单独的键。

我希望实现的输出是:

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
    /insights/
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Insights
  </div>
</div>

<div class="productCard">
  <div class="productCard__header">
    <!-- url here-->
    /statistics/
  </div>
  <div class="productCard__body">
    <!--subheader here -->
    Statistics
  </div>
</div>

我哪里错了?

标签: phphtmlarrays

解决方案


您正在遍历数组每个元素的内部数据

for() 遍历主数组,然后您的 foreach() 遍历各个组件。

由于您的内部数组是一个关联数组(键由您定义),这意味着您可以使用 [''] 符号直接访问它们。

有很多不同的方法可以做到这一点,但我建议一个循环,然后提取你的个人值:

尝试这个:

<?php
foreach($pages as $key => $value) { ?>

  <div class="productCard">
    <div class="productCard__header">
      <!-- url here-->
<?php echo $value['url']; ?>
    </div>
    <div class="productCard__body">
      <!--subheader here -->
      <?php echo $value['subheader']; ?>
    </div>
  </div>

<?php
}
?>

推荐阅读