如何在不知道有多少项的情况下使用foreach循环遍历多维数组


How do I loop through a multidimensional array with foreach without knowing how many items there are?

我有一个数组,如下所示:

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)数量的图像URL。

您可以在此处轻松使用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
}

如果我理解你的问题,那就很容易了。循环遍历每个结果,然后在foreach中有另一个foreach,它循环遍历图像。例如

foreach($product as $prod)
{
 //logic goes here
 foreach($prod['images'] as $img)
 {
   //do stuff with image
 }
}