1, "sid" => "s00123-6ren">
gpt4 book ai didi

php - 在php中按值对多维数组进行分组

转载 作者:行者123 更新时间:2023-12-03 23:46:39 24 4
gpt4 key购买 nike

我有一个数组,其中包含数据如下,

$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");

数组包含类(class)和学生 ID,我想对该数组进行分组,以便根据类(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"
)
)

)

我正在使用的代码是,

$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;
}
}

这对我有用,但是有没有更好的解决方案,或者任何 PHP 内置函数可以做到这一点?

最佳答案

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

关于php - 在php中按值对多维数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6069150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com