Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach & Arrays in PHP

I'm terribly confused on how I should be writing this function...it basically scores a test, and it WORKS for one user's values.

Let's say I want the values for the following user: $id = 2...this works! If $id = array(2,3,4,5) it doesn't work!

function get_score_a($id){
    // Case 4
    foreach($this->get_results_a($id,4)->row() as $key=>$a){
        if ($a >= 2 && $a <= 4) {
            $score_a += 2;
        } else if ($a > 4 && $a < 8) {
            $score_a += 3;
        } else if ($a > 8) {
            $score_a += floor($a - 8) * .5;
            $score_a += 3;
        }
    };

    return $score_a;
}


function get_results_a($id, $method) {
        $select_cols = array(
                            1 => array('a_1','a_2','a_4'),
                            2 => array('a_6','a_8','a_11','a_12','a_14'),
                            3 => array('a_3','a_10'),
                            4 => array('a_5','a_7','a_9','a_13')
                            );
        return $this->db->select($select_cols[$method])
                        ->where_in('id', $id)
                        ->get('be_survey');
    }

This returns a score...however, if I run multiple ids...it just adds up all the numbers, I think...

Instead I need this to output separate scores for individual users...

May it be noted that I'm a total noob! So vivacious explanations are very much appreciated. :)

Edit Please review my code...as I should have been more clear! Sorry! I apologize! In summation, this selects the correct values from the table, based on

And yes, my eyes hurt too! Edit I am too hasty! This is a Codeigniter project!

like image 926
Kevin Brown Avatar asked Dec 07 '25 09:12

Kevin Brown


1 Answers

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)

like image 72
Stoic Avatar answered Dec 10 '25 00:12

Stoic