开发者

iteration in foreach [closed]

开发者 https://www.devze.com 2023-04-01 10:23 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.
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--;
  }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消