iteration in foreach [closed]
foreach($tests as $i => $test){
if ($test->getNumber() == 2) {
echo $i . $getName() ;
} else {
$i--;
}
}
for example:
number | name
开发者_StackOverflow社区 1 | aaa
2 | bbb
1 | ccc
2 | vvv
2 | ccc
show me:
$i $name
2 bbb
4 vvv
5 ccc
instead of:
$i $name
1 bbb
2 vvv
3 ccc
how can i fix it?
I think you are trying to do:
$i = 0;
foreach($tests as $key => $test){
if ($test->getNumber() == 2) {
echo ++$i . $getName() ;
}
}
Beacuse foreach is returning you the index of $test inside $tests array so your $tests array is:
$tests[0] => 1 aaa
$tests[1] => 2 bbb
$tests[2] => 1 ccc
$tests[3] => 2 vvv
$tests[4] => 2 ccc
$i which is rewritten each iteartion by foreach statement.
Try this (using another counter):
$j = 0;
foreach($tests as $i => $test){
if ($test->getNumber() == 2) {
$j++;
echo $j . $getName() ;
}
}
There is no point in $i--
as it's overwritten in the loop.
$counter = 0;
foreach($tests as $i => $test){
if ($test->getNumber() == 2) {
++$counter;
echo $counter . $getName() ;
}
}
The problem is that you are printing the number from the array, rather than creating new numbering.
Untested but should work.
foreach($tests as $i => $test){
$num = '0';
if ($test->getNumber() == 2) {
echo $num . $getName() ;
$num++;
} else {
$i--;
}
}
精彩评论