[英]How to compare attribute to next element's one
How to get value of the next ORM element in foreach? 如何获取foreach中下一个ORM元素的值? I need something like that: 我需要这样的东西:
$users = ORM::factory('Users')
->order_by('category', 'ASC')
->find_all();
foreach($users as $user)
{
if($user->category != next($user->category))
{
echo 'Next category user';
}
}
Comparing to the next item can be difficult at times (like these). 有时很难与下一项进行比较(像这样)。 However, comparing to the previous one is usually quite easy. 但是,与前一个相比通常很容易。
Eg like this: 例如:
$users = ORM::factory('Users')
->order_by('category', 'ASC')
->find_all();
$previousCategory = null;
foreach($users as $user)
{
if($user->category != $previousCategory)
{
echo 'Next category user';
}
$previousCategory = $user->category;
}
One way is to manually seek to the next element, take the values you want, then reset back to where you were. 一种方法是手动查找下一个元素,获取所需的值,然后重设回原来的位置。 It's pretty messy but it'll do what you want: 杂乱无章,但可以满足您的要求:
foreach($users as $user)
{
$current_key = $users->key();
$next_category = $users->seek($current_key + 1) ? $users->current()->category : NULL;
$users->seek($current_key);
if($next_category && $user->category != $next_category)
{
echo 'Next category user';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.