phparraysmultidimensional-arraygroupingsub-array

Group row data from a 2d array by one column and populate the group's subarray with another column


I have an array, which contains data as follows.

$students_array = [
    ["class" => 1, "sid" => "s00123"],
    ["class" => 2, "sid" => "s00456"],
    ["class" => 1, "sid" => "s008765"],
    ["class" => 1, "sid" => "s008987"],
    ["class" => 3, "sid" => "s008789"],
    ["class" => 3, "sid" => "s008543"]
];

The array contains class and student id, I want to group this array in such a way that it will be grouped based on class.

[
    1 => [
        ["sid" => "s00123"],
        ["sid" => "s008765"],
        ["sid" => "s008987"],
    ],
    2 => [
        ["sid" => "s00456"],
    ]
    3 => [
        ["sid" => "s008789"],
        ["sid" => "s008543"],
    ]
]

The code that I am using is,

$class_array = array();
foreach ($students_array as $sa) {
    if (isset($class_array[$sa['class']])) {
        $inner_array = array();
        $inner_array["sid"] = $sa['sid'];
        $class_array[$sa['class']][]= $inner_array;
    } else {
        $inner_array = array();
        $inner_array["sid"] = $sa['sid'];
        $class_array[$sa['class']][]= $inner_array;
    }
}

which works for me, but is there any better solution, or any PHP built-in functions to do so?


Solution

  • $class_array = array();
    foreach ($students_array as $sa) {
        $class_array[$sa['class']][] = array('sid' => $sa['sid']);
    }