php - 基于多维数组生成标记
问题描述
我有以下内容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>
我哪里错了?
解决方案
您正在遍历数组每个元素的内部数据
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
}
?>
推荐阅读
- authentication - IBM MQ 认证和授权
- typescript - 如何通过 Typscript 安装解决这个问题?
- leaflet - 如何防止 Leaflet/Mapserver(WMS) 中的标签/符号重复/剪切
- pandas - 熊猫读入一列
- maven - 如何将 maven 依赖项添加到打包的 jar 中?包装类型为 eclipse-plugin
- c# - ASP.NET MVC 5 插入语句冲突 FK
- javascript - 当另一个函数在javascript中启动时如何停止一个函数?
- python - MobileBy.ANDROID_UIAUTOMATOR 不可调用
- python - tensofrlow2 中是否有将张量输出类别与原始输入标签匹配的函数?
- android - 当我在另一个应用程序中打开文档时,URI 错误