首页 > 解决方案 > 检查 foreach 循环中的下一个对象中是否存在值

问题描述

首先感谢您花时间阅读本文。我的问题是如何检查 foreach 循环中的对象中是否存在值到目前为止,我已经完成了这项工作。

SQL查询获取消息和值以检查每行之间的分钟差异(检查用户是否在一分钟内发布消息,以便我可以在该组的最后一条消息的末尾显示个人资料图像)

"SELECT *,id, sentOn, timestampdiff(minute,sentOn,(SELECT sentOn FROM messages t2 WHERE t2.id < t1.id ORDER BY t2.id DESC LIMIT 1)) AS diff FROM messages t1" 

并简单地检索消息

$stmt = $this->db->prepare($sql);
        $stmt->execute();
        $messages = $stmt->fetchAll(PDO::FETCH_OBJ); 

并显示消息

foreach ($messages as $user) {
    $next = next($messages);

    echo 'User: '.$user->message.'<br/>'.((@$next->diff != '0') ? 'Profile image. chats ends at SUN 12:20 PM<br/><br/>' : '');
}

Here's result 
Jon: Hi
Jon: hello
Profile image. 
Chats end at SUN 12:20 PM

Jon: hello?
Profile image. 
Chats end at SUN 12:20 PM

Jon: remember me?
Profile image. 
Chats end at SUN 12:20 PM

抱歉,如果这看起来令人困惑,让我解释一下,所以我想检查该消息是否是该组的最后一条消息(以上查询),然后在该方法执行的消息末尾显示配置文件图像。但是如果我在循环中从 $next->diff 中删除@,它将抛出非对象的获取属性'diff'

标签: phpmysql

解决方案


你应该检查是否$next存在。如果可以用empty例如:

(!empty($next) && $next->diff != '0') 
    ? 'Profile image. chats ends at SUN 12:20 PM<br/><br/>' : ''

推荐阅读