我如何将所有student_id聚集在一起并制作一个子阵列()

时间:2017-01-09 16:16:03

标签: php arrays

这是我的数组:

Array
    (
        [0] => Array
            (
                [student_id] => 22
                [skill_id] => 3
                [gd_score] => 4
            )

        [1] => Array
            (
                [student_id] => 22
                [skill_id] => 63
                [gd_score] => 5
            )

        [2] => Array
            (
                [student_id] => 23
                [skill_id] => 3
                [gd_score] => 9
            )

        [3] => Array
            (
                [student_id] => 23
                [skill_id] => 128
                [gd_score] => 10
            )

        [4] => Array
            (
                [student_id] => 24
                [skill_id] => 63
                [gd_score] => 10
            )

        [5] => Array
            (
                [student_id] => 24
                [skill_id] => 128
                [gd_score] => 2
            )
    )

如何将所有student_id组合在一起并制作子阵列()?

1 个答案:

答案 0 :(得分:2)

使用此代码,您将获得一个包含所有学生的数组。索引将是学生ID,它将包含一组所有{skill_id,gd_score}。

$students = array();
foreach ($array as $row){
    $student_id = $row['student_id'];
    $students[$student_id][] = array('skill_id'=>$row['skill_id'],'gd_score'=>$row['gd_score']);
}
print_r($students);