【发布时间】: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)?