如何检查 imagesid 和 imgs 是否存在数组以避免未定义的偏移错误?
How can I check if array is exists for the imagesid and for the imgs to avoiding Undefined offset error?
我想检查 imagesid 和 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
}
?>
听起来并不是所有帖子都有图片。您可能想确保在执行此行 foreach($imgs[$imagesID] as $img)
之前存在 $imgs[$imagesID]
。一种解决方案是 "wrap" if(isset($imgs[$imagesID])
中的 foreach
我想检查 imagesid 和 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
}
?>
听起来并不是所有帖子都有图片。您可能想确保在执行此行 foreach($imgs[$imagesID] as $img)
之前存在 $imgs[$imagesID]
。一种解决方案是 "wrap" if(isset($imgs[$imagesID])