【问题标题】:Generate markup based on multidimensional array基于多维数组生成标记
【发布时间】:2021-12-13 05:32:37
【问题描述】:

我有以下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>

我哪里错了?

【问题讨论】:

  • $pages 不是关联数组,为什么要使用array_keys($pages)

标签: php html arrays


【解决方案1】:

你正在循环遍历数组每个元素的内部数据

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
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2016-07-28
    • 1970-01-01
    • 2014-08-10
    • 2014-07-16
    相关资源
    最近更新 更多