开发者

group a multidimensional array by values in php

开发者 https://www.devze.com 2023-03-07 00:50 出处:网络
I have an array, which contains data as follows, $students_array = array(); $students_array[] = array(\"class\" => 1, \"sid\" => \"s00123\");

I have an array, which contains data as follows,

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

the array contains class and student id, I want to group this array in such away that it will be grouped based on开发者_如何学编程 class,

Array
(
  [1] => Array
    (
        [0] => Array
            (
                [sid] => "s00123"
            )

        [1] => Array
            (
                [sid] => "s008765"
            )

        [2] => Array
            (
                [sid] => "s008987"
            )

    )

  [2] => Array
    (
        [0] => Array
            (
                [sid] => "s00456"
            )
    )

  [3] => Array
    (
        [0] => Array
            (
                [sid] => "s008789"
            )
        [1] => Array
            (
                [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?


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


I think your code could be rewritten as (untested):

$out = array();
foreach ($students_array as $row) {
    extract($row);
    if (!defined($out[$class])) {
        $out[$class] = array();
    }
    $out[$class][] = array('sid' => $sid);
}

I believe you should be able to use array_map() to build this array but for the sake of readability I'd probably run with what you have at the moment.

0

精彩评论

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