开发者

Looping over with arrays by grouping matching values

开发者 https://www.devze.com 2023-04-13 09:18 出处:网络
I am writing a module for my website, that gives a breakdown of test results, I need to get someout put similar to this,

I am writing a module for my website, that gives a breakdown of test results, I need to get someout put similar to this,

Test Title

Average Mark 85%

Test Title 2

Average Mark 12%

The array I am getting 开发者_如何学编程from my database looks like this,

    Array
(
    [0] => Array
        (
            [result_id] => 11
            [test_taken] => 2011-10-04 16:22:59
            [mark] => 5
            [retaken] => false
            [tests_test_id] => 4
            [test_title] => Website Development CSS Basics
            [test_slug] => website-development-css-basics
            [mark_needed] => 90
            [retake] => Yes
            [topic_id] => 402
            [topics_topic_id] => 402
        )

    [1] => Array
        (
            [result_id] => 12
            [test_taken] => 2011-10-04 16:30:02
            [mark] => 50
            [retaken] => false
            [tests_test_id] => 5
            [test_title] => Another Test
            [test_slug] => another-test
            [mark_needed] => 10
            [retake] => No
            [topic_id] => 402
            [topics_topic_id] => 402
        )

)

This my query currently,

$this->db->select('results.result_id, results.test_taken, results.mark, results.retaken, results.tests_test_id, tests.test_title, tests.test_slug, tests.mark_needed, tests.retake, topics.topic_id, tests.topics_topic_id')
    ->from('results')
    ->join('tests', 'tests.test_id = results.tests_test_id', 'left')
    ->join('topics', 'topics.topic_id = tests.topics_topic_id', 'left');

    $query = $this->db->get();
    return $query->result_array();

I need to somehow group all the results the have same test id so that I can then get the mean average of the results using the mark key.

Is this possible in PHP?


This is the kind of thing you should get the database to do for you. Something along the lines of:

SELECT AVG(mark) FROM test_results GROUP BY tests_test_id


Create a new array and then loop though - adding as you go ?

$sumArray = array();

foreach ($myArray as $key=>$val) {
    $sumArray[$key]+=$val;
}

print_r($sumArray['test_id']);
0

精彩评论

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

关注公众号