Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检测数组中组的最后一个元素_Php_Arrays_Foreach_Grouping - Fatal编程技术网

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

Php 检测数组中组的最后一个元素,php,arrays,foreach,grouping,Php,Arrays,Foreach,Grouping,我有一个数组。它按子数组中的值分组: [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循环中,我想知道元素何时是其组中

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

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

只需跟踪当前组并将其与循环中的新组进行比较。我不需要数组中的最后一个元素。在foreach循环中,我想知道元素最后一次出现在组中的时间。例如,当指针指向4=>[id=>1,group=>3]时,