检测数组中组的最后一个元素

Detect last element of group in an array

我有一个数组数组。它按子数组中的值分组:

[2  => [id=>5, group=>3],
6  => [id=>8, group=>3],
4  => [id=>1, group=>3],
2  => [id=>11,group=>2],
26 => [id=>41,group=>2],
5  => [id=>55,group=>6],]

foreach 循环中,我想知道元素何时是其组中的最后一个。 如果没有第二个 foreach 周期,我怎么能做到呢?

试试这个..

    $arr = array(0 => array(id=>1,group=>"1"),
             1 => array(id=>2,group=>"2"),
             2 => array(id=>3,group=>"1")
);
$last=end($arr);
echo $last['group'];

如果不获取下一个元素,您无法知道它何时是最后一个,但是您可以确定它何时更改,因此如果您在 foreach 循环开始时使用它,您可以在组的最后一个元素:

$group = 0;
foreach ($arr as $key => $value)
{
  if ($group > 0 && $value['group'] !== $group)
  {
    // start of new group, excluding the very first one
    $group = $value['group'];

    // do the things you want to do to separate the groups

  }
  ...
}

假设数组按组排序,并且同一组的元素之间没有空格。

$previousGroup = false;
$lastIndex = -1;
foreach($arr as $key=>$value) {
  if($previousGroup !== false && $previousGroup !== $value['group']) {
    echo $lastIndex.' is last index of the group '.$previousGroup;
  }

  //do something

  $previousGroup = $value['group'];
  $lastIndex = $key;
}
if($previousGroup !== false) {
  //handle the last group
  echo $lastIndex.' is last index of the group '.$previousGroup;
}