如何将属性与下一个元素的属性进行比较

时间:2022-06-04 21:26:52

How to get value of the next ORM element in foreach? I need something like that:

如何获得foreach中下一个ORM元素的值?我需要这样的东西:

   $users = ORM::factory('Users')
       ->order_by('category', 'ASC')
       ->find_all();
    foreach($users as $user)
    {
       if($user->category != next($user->category))
       {
          echo 'Next category user';
       }
    }

2 个解决方案

#1


1  

Comparing to the next item can be difficult at times (like these). However, comparing to the previous one is usually quite easy.

有时候比较下一个项目很困难(比如这些)。但是,与前一个相比通常很容易。

E.g. 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;
}

#2


0  

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';
   }
}

#1


1  

Comparing to the next item can be difficult at times (like these). However, comparing to the previous one is usually quite easy.

有时候比较下一个项目很困难(比如这些)。但是,与前一个相比通常很容易。

E.g. 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;
}

#2


0  

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';
   }
}