开发者

How to add object to array with foreach and switch, case

Hi I wanna ad an object to an array

开发者_运维技巧

As you can see below I run through an array and based on the last character i make and switch case, then I wanna construct a new array and add the secon last character to this new array, so I can mannage to sum this new array and print or echo the sum.

foreach ($answer as $value) {
  $last=substr($value,-1);
  $score=substr($value,-2,1);
  switch($last){
    case a:
      $a=array();
      array_push($a,$score);
      break;
    case b:
      $b=array();
      array_push($b,$score);
      break;
  }
}

In my html table I do this:

echo array_sum($a)

I can make it work if I add a digit like array_push($a,'2'); but with the object it just overwrite the first one. what do I do wrong here?


You're clearing your arrays on every pass. Define them before the foreach loop:

$a = array();
$b = array();

foreach ($answer as $value) {
  $last=substr($value,-1);
  $score=substr($value,-2,1);
  switch($last){
    case a:
      array_push($a,$score);
      break;
    case b:

      array_push($b,$score);
      break;
  }
}


You're creating a new array each time one of those case statements matches, which means you're essentially throwing away all the previous times the statement matched, starting from scratch each time. Move the $a = array() and $b = array() OUTSIDE the loop, so the arrays are created only once:

$a = array();
$b = array();
foreach (...) {
   ....
}

should fix up the problem

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜