【问题标题】:Looping over with arrays by grouping matching values通过对匹配值进行分组来循环使用数组
【发布时间】:2011-10-13 19:27:27
【问题描述】:

我正在为我的网站编写一个模块,它给出了测试结果的细分,我需要得到一些类似的输出,

测试标题
平均分 85%

测试标题 2
平均分 12%

我从数据库中获取的数组如下所示,

    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->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();

我需要以某种方式对具有相同测试 ID 的所有结果进行分组,以便我可以使用标记键获得结果的平均值。

这在 PHP 中可行吗?

【问题讨论】:

  • 你可以使用更智能的查询

标签: php codeigniter foreach average


【解决方案1】:

这是您应该让数据库为您做的事情。大致如下:

SELECT AVG(mark) FROM test_results GROUP BY tests_test_id

【讨论】:

    【解决方案2】:

    创建一个新数组,然后循环 - 随时添加?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 2018-11-03
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多