php - 从多维数组中取值
问题描述
我有一个多维数组:
$carousel = array(
array(
"cite" => 'title_1',
"blockquote" => 'description_1',
"imgs" => 4
),
array(
"cite" => 'title_2',
"blockquote" => 'description_2',
"imgs" => 2
)
);
我想将此信息包装在 html 中并将 n 个图像作为 imgs 值回显。我只能回显 n 个图像,但我想分别关联引用和块引用。
我尝试使用 foreach 但没有成功:
foreach ($carousel as $images){
foreach ($images as $key => $value){
echo $value . "\n";
for ($i = 0; $i < $value; $i++) {
echo("image url" . "\n\n");
}
}
}
当我回显 $value 和图像时,我获得了所有值:
title_1
description_1
4
image url
image url
image url
image url
title_2
description_2
2
image url
image url
但我想像这样单独使用它们
<cite>title_1</cite>
<blockquote>description_1</blockquote>
<img></img> //4 times as specified in "imgs"
<img></img>
<img></img>
<img></img>
<cite>title_2</cite>
<blockquote>description_2</blockquote>
<img></img> //2 times as specified in "imgs"
<img></img>
我很感激任何建议。
解决方案
您有一个不需要的额外 foreach 循环。
尝试这个:
//loop through array
foreach($carousel as $values) {
//echo cite info
echo "<cite>{$values['cite']}</cite>";
//echo blockquote info
echo "<blockquote>{$values['blockquote']}</blockquote>";
//loop until you have the same amount of <img> tags as defined in the `imgs` array element.
for ($x = 1; $x <= $values['imgs']; $x++) {
echo "<img></img>";
}
}
推荐阅读
- react-native - 如何在 react-navigation v5 中导航到 postId?
- vba - MS Access 数据库中的通用术语搜索,可以吗?
- reactjs - 如何为从 TypeScript 中的 React Child 组件接收数据的函数声明类型
- dataframe - 将 iterrows 中的值存储在数据框中
- javascript - 将文本从文本区域复制到剪贴板 - Python
- kubernetes - 如何递归获取Kubernetes owner资源的依赖资源
- r - 将 ID 字符串重新编码为其他字符串的最佳实践
- sql - TypeOrm 生成关系图
- django - Django -- 为 TMDB API 请求将函数视图转换为基于类的视图
- python - 是否可以 pyscreez.locate(needleImage, haystackImage): 无需每次都从文件中读取 haystackImage?