简体   繁体   English

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

[英]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.

相关问题 如何将数组的每个元素相互比较? - How to compare every element of array with one another? 如何将多维数组与一个数组元素进行比较? - How to compare a multidimensional array with one array element? 如何生成下一个序列号并在php中比较第一个序列号? - How to generate a next series number and compare first one in php? 如何将同一表中的一个元素与另一个元素进行比较 - How to compare one element from same table to another element 如何查询mySQL数据库的一个属性并将结果与​​表单变量进行比较? - How to query one attribute of mySQL database and compare results to a form variable? 比较数组列表与数组中的下一个列表 - Compare array lists with the next one in an array 如何比较两个数组并从一个数组中删除匹配元素以进行下一个循环? - How to compare two arrays and remove matching elements from one for the next loop? 如何根据动态提供的ID更新元素的占位符属性? - How to update an element's placeholder attribute based on a dynamically fed id? 如何访问XML nth元素的属性值和属性值 - How to access an XML nth element's property value and attribute value 如何在php中的mysql查询中将一个表单元素值传递给下一个表单元素? - How do I pass one form element value to the next form element for mysql query in php?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM