【发布时间】:2014-01-02 02:24:06
【问题描述】:
好吧,我坚持这个。 我有一个嵌套在另一个 foreach 循环中的 foreach 循环。现在在某些情况下,我需要使用相同的键再次运行外循环。 虽然有这个函数 prev($array),它将迭代器设置到前一个位置,但这似乎不起作用,php 文档说
由于 foreach 依赖于 >internal 数组指针,因此在循环内更改它可能会导致意外行为。
我正在处理的数组是一个关联数组,所以显然我不能轻易地切换到整数索引迭代。
$arrLocalCopy = $this->arrPrintOut;
$groupCounter = 0;
foreach($this->arrPrintOut as $kOne => $rowA){
//first and last row contain titles and totals, so we skip them
if($groupCounter < 1 || $groupCounter == sizeof($this->arrPrintOut)-1 ){ $groupCounter++; continue; }
$rowCounter = 0;
foreach($arrLocalCopy as $k => $rowB){
//skip rows that are "before" the outer loops row, as we want to compare only rows below the row we compare to.
if ($rowCounter <= $groupCounter || $rowCounter == sizeof($arrLocalCopy)-1 ) { $rowCounter++; continue; }
//If those values are the same, then values belong to the same group and must be summed together.
if($rowA['t']==$rowB['t'] && $rowA['y']==$rowB['y'] && $rowA['g']==$rowB['g'] && $rowA['q']==$rowB['q'])
{
//if values are the same, then data belongs to one group, lets group them together.
$this->arrPrintOut[$kOne]['s'] += $rowB['s'];
$this->arrPrintOut[$kOne]['b'] += $rowB['b'];
$this->arrPrintOut[$kOne]['v'] += $rowB['v'];
$this->arrPrintOut[$kOne]['r'] += $rowB['r'];
$this->arrPrintOut[$kOne]['k'] += $rowB['k'];
$this->arrPrintOut[$kOne]['n'] += $rowB['n'];
$this->arrPrintOut[$kOne]['m'] += $rowB['m'];
$this->arrPrintOut[$kOne]['l'] += $rowB['l'];
unset($this->arrPrintOut[$k]); //row has been grouped to the current row, so we remove it from the array and from the copy.
unset($arrLocalCopy[$k]);
prev($this->arrPrintOut); //we need to run the outer loop with the same key again, as probably there is another row which could be grouped together with this row.
$groupCounter--;
}
$rowCounter++;
}
$groupCounter++;
}
【问题讨论】:
-
然后使用
for循环,与$key = key($array)和$value = $array[$key]。所以你可以做prev($array)。 -
非常感谢,我会朝这个方向看看。我假设你的意思是。比如 for($i...) { $key = key($array[$i]);...
-
是的,我就是这个意思:-)
-
但是如果数组像 $array = array( 1 => "a", 6 => "b", );不是 $array = array("1" => "a", "6" => "b", );我的意思是它如何区分 array[6] 和 array[1]==second 元素。