大家好,感谢您抽出时间。我的问题是关于。
我正在尝试循环遍历文件夹中的图像以及数据库中的帖子,最终结果如下所示:
Post 1
Image 1Post 2
Image 2Post 3
Image 3
目前我得到这个结果:
Post 1
Image 1Post 1
Image 2Post 1
Image 1Post 2
Image 1Post 2
Image 2Post 2
Image 3
我不想要这个结果。
下面是我的代码:
$post_info = get_posts();
foreach ($post_info as $info){
$photos = glob('design/img/*');
foreach($photos as $photo) {
echo " <a href='feed.php?pid=".$info['post_id']." ' >
<div style='background:#FFF5C3'> <br> <h2> ".$info['person_mentioned']." </h2>
<h3 style='color: black'> ".$info['body']." </h3> </div> </a>";
echo " <img src='{$photo}' width='285px' height='200px' style='border: 5px solid black'>";
}
}
感谢您的宝贵时间。
最佳答案
试试这个(减去潜在的语言细节,因为我实际上没有运行来检查这段代码)..它基本上是一个常规的 for 循环而不是 foreach。
$post_info = get_posts();
$photos = glob('design/img/*');
if (count($post_info) === count($photos)) { // According to your requirement, the counts would be the same
$count = count($post_info);
for ($i = 0; $i < $count; $i++) {
$info = $post_info[$i];
$photo = $photos[$i];
echo " <a href='feed.php?pid=".$info['post_id']." ' > <div style='background:#FFF5C3'> <br> <h2> ".$info['person_mentioned']." </h2>
<h3 style='color: black'> ".$info['body']." </h3> </div> </a>";
echo " <img src='{$photo}' width='285px' height='200px' style='border: 5px solid black'>";
}
}
希望有帮助:)
关于php - foreach 循环未显示所需结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12341667/