php - 检查 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'
解决方案
你应该检查是否$next
存在。如果可以用empty
例如:
(!empty($next) && $next->diff != '0')
? 'Profile image. chats ends at SUN 12:20 PM<br/><br/>' : ''
推荐阅读
- azure-api-management - 即使从 APIM 中删除客户端证书,它们似乎也可以访问
- javascript - 我的 Spring Boot 应用程序没有更新我的 JavaScript 代码,而是使用旧的
- c# - .net 无缝 c# + f#
- javascript - 如何处理动态生成页面的 CSP
- php - 如何在 Wordpress ( WP ) 中将类别定义为具有颜色值的变量?
- javascript - 通过onload使用javascript删除元素
- python - tensorflow 将参数复制到另一个网络(相同架构),例如 DQN
- c - 比较相同的字符串文字总是正确的吗?
- javascript - 如何使用自定义 JavaScript 在 Google 跟踪代码管理器中创建变量以将另一个 GTM 变量日期转换为 ISO 8601 格式?
- codenameone - 屏幕锁定时应用程序事件冻结或不刷新 + 代号一