在php中按值对多维数组进行分组
我有一个数组,其中包含如下数据,
$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");
该数组包含班级和学生 ID,我想对该数组进行分组,以便根据班级进行分组,
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 内置函数可以做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的代码可以重写为(未经测试):
我相信你应该能够使用
array_map()
来构建这个数组,但为了可读性,我可能会用你所拥有的来运行那一刻。I think your code could be rewritten as (untested):
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.