我想检查数组是否存在imageid和imgs或imagesid和imgs具有相同的值,并且它不会抛出Notice: Undefined offset:
错误消息。
我有这个代码来获取帖子的相关图像:
$sql = "SELECT * FROM multiple_image";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$imgs[$row['imageid']][$row['id']]= "<img width='' src='../images/".$row['name']."' >"; // array of image id's, with arrays of images inside them.
}
}
$sql = "SELECT * FROM posts ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$commentsToImages[$row['commentid']] = $row['imagesid']; // array of post id's to picture ids
$comments[$row['commentid']] = $row['comment']; // array of post id's to comment text.
}
}
此代码使用内容呈现所有相关图像:
foreach($commentsToImages as $commentID =>$imagesID) {
?>
<div class='main'>
<div class='comments'>
<?php echo $comments[$commentID]; // render the comment ?>
</div>
<div class='pics'>
<?php
foreach($imgs[$imagesID] as $img) { // foreach loop that will render all the images...
echo $img;
}
?>
</div>
</div>
<?php
}
?>
听起来并非所有帖子都有图像。您可能希望确保在此行$imgs[$imagesID]
执行之前存在foreach($imgs[$imagesID] as $img)
。一种解决方案是将一个foreach“包裹”在if(isset($imgs[$imagesID])
中