我有一个这样的数组:
Array
(
[count] => 2
[results] => Array
(
[0] => Array
(
[title] => My Title 1
[description] => My amazing description
[Images] => Array
(
[0] => Array
(
[pic_url] => https://my.pic.url/01/pic01-001.jpg
)
)
)
[1] => Array
(
[title] => My Title 2
[description] => Yet another amazing description
[Images] => Array
(
[0] => Array
(
[pic_url] => https://my.pic.url/02/pic02-001.jpg
)
[1] => Array
(
[pic_url] => https://my.pic.url/02/pic02-002.jpg
)
)
)
)
)
数组中可能有1个项目或100个产品,每个产品的数量可能介于1-5 [Images]
之间。我怎样才能遍历每一个,以便最终我有类似的东西:
Title:
My Title 2
Description:
Yet another amazing description
Images:
https://my.pic.url/02/pic02-001.jpg
https://my.pic.url/02/pic02-002.jpg
我能够以$decoded['results']['0']['title']
为例获得标题,但我无法弄清楚如何显示每个标题以及每个标题的未知(1到5)图像网址数量
答案 0 :(得分:3)
您可以在此轻松使用foreach
。此外,请务必首先迭代result
密钥,例如$arr['result']
。如果此代码将放在前端,您可以执行以下操作:
$arr = array( /* your array content */ );
foreach ($arr['results'] as $result) {
?>
<div>
<div>Title:<?= $result['title'] ?></div>
<div>Description:<?= $result['description'] ?></div>
<div>
Images:
<?php foreach ($result['Images'] as $image) { ?>
<div><?= $image['pic_url'] ?></div>
<?php } ?>
</div>
</div>
<?php
}
答案 1 :(得分:1)
如果我理解你的问题,这很容易。循环遍历每个结果然后在foreach内有另一个foreach循环通过图像。例如
foreach($product as $prod)
{
//logic goes here
foreach($prod['images'] as $img)
{
//do stuff with image
}
}