Foreach & Arrays in PHP Foreach & Arrays in PHP codeigniter codeigniter

Foreach & Arrays in PHP


Firstly, there is no row() for arrays.. just use foreach ($array as $key=>$value)
Secondly, inside the foreach loop $score_b is being incremented on each run with its previous value. So, your code is outputting the sum of all player scores.
use:

foreach(array(5,5,5,6,7,78,8,7,7,6,5) as $key=>$a){         if ($a >= 0 && $a <= .5) {             $score_b[$key] += 0;         } else if ($a > .5 && $a < 2) {             $score_b[$key] += 1;         }     else if ($a > 2 && $a < 4) {             $score_b[$key] += 2;         }           else if ($a > 4) {          $score_b[$key] += floor($a - 8) * .5;             $score_b[$key] += 2;         }     };

$score_b will now be an array of scores.

EDIT:Add the following in your code:

$id = array(2,3,4,5);function get_score_array($ids) {    foreach ($ids as $id) {        $scores[$id] = get_score_a($id);    }    return $scores;}

$scores will now be an array of $id=>$score pairs.
Also, adjust the above code, as per your framework (which I guess you are using)


There is no such method called row() on array. In fact, an array isn't strictly an object, so it doesn't have methods.

So, first of all, get rid of the ->row() invocation.

Second, where are you pushing these scores onto an array? I don't see where that happens in your code. Initialize an empty array before the foreach loop, and push the $score_b variable onto the array at the end of the loop.


Set a $userID variable outside the foreach loop like this:

$userScores = array(    'bobby' = > array(5,5,5,6,7,78,8,7,7,6,5),    'sue' = > array(5,5,5,6,7,78,8,7,7,6,5),    'joe' = > array(5,5,5,6,7,78,8,7,7,6,5));foreach($userScores as $name => $a){    $score_b[$name] = 0; //initialize    if ($a >= 0 && $a <= .5) {         $score_b[$name] += 0;    } else if ($a > .5 && $a < 2) {    $score_b[$name] += 1;     } else if ($a > 2 && $a < 4) {         $score_b[$name] += 2;     }       else if ($a > 4) {      $score_b[$name] += floor($a - 8) * .5;         $score_b[$name] += 2;     } };

your end result should be something like (I didn't do any actual math)

$score_b['bobby'][100]$score_b['sue'][75]$score_b['joe'[90]