本文概述
- 按功能分组
- 用法
在本文中, 我们将与你分享一个小片段, 使你可以按某个键对数组的项进行分组。
按功能分组以下函数创建一个新数组, 该数组使用关联结构存储原始输入数组的所有数据。迭代一次, 为具有指定键的数据值的新数组创建一个新键(因此, 当出现具有相同值的新项目时, 它将被推入该键)。如果输入数组的某项不包含已定义的键, 则它将被推入新数组的空字符串键中:
<
?php/** * Function that groups an array of associative arrays by some key. * * @param {String} $key Property to sort by. * @param {Array} $data Array that stores multiple associative arrays. */function group_by($key, $data) {$result = array();
foreach($data as $val) {if(array_key_exists($key, $val)){$result[$val[$key]][] = $val;
}else{$result[""][] = $val;
}}return $result;
}
用法考虑以下数据结构:
<
?php $data = http://www.srcmini.com/array(array("id" =>
1, "name" =>
"Bruce Wayne", "city" =>
"Gotham", "gender" =>
"Male"), array("id" =>
2, "name" =>
"Thomas Wayne", "city" =>
"Gotham", "gender" =>
"Male"), array("id" =>
3, "name" =>
"Diana Prince", "city" =>
"New Mexico", "gender" =>
"Female"), array("id" =>
4, "name" =>
"Speedy Gonzales", "city" =>
"New Mexico", "gender" =>
"Male"));
我们有4个简单的项目, 我们想按一个属性(例如性别)对它们进行分组, 因此按该键对数据进行分组的代码为:
<
?php// Group data by the "gender" key $byGroup = group_by("gender", $data);
// Dump resultecho "<
pre>
" . var_export($byGroup, true) . "<
/pre>
";
【如何在PHP中按键对关联数组进行分组】转储的数组将具有以下结构:
array ('Male' =>
array (0 =>
array ('id' =>
1, 'name' =>
'Bruce Wayne', 'city' =>
'Gotham', 'gender' =>
'Male', ), 1 =>
array ('id' =>
2, 'name' =>
'Thomas Wayne', 'city' =>
'Gotham', 'gender' =>
'Male', ), 2 =>
array ('id' =>
4, 'name' =>
'Speedy Gonzales', 'city' =>
'New Mexico', 'gender' =>
'Male', ), ), 'Female' =>
array (0 =>
array ('id' =>
3, 'name' =>
'Diana Prince', 'city' =>
'New Mexico', 'gender' =>
'Female', ), ), )
如你所见, 你将收到一个新的关联数组, 其中包含数据的所选键的所有可能值(在这种情况下为性别), 因此我们有2个组, 即Male和Female。如果你将另一个属性(例如城市)分组, 则将遵循相同的逻辑:
<
?php// Group data by the "city" key $byGroup = group_by("city", $data);
// Dump resultecho "<
pre>
" . var_export($byGroup, true) . "<
/pre>
";
其输出将是:
array ('Gotham' =>
array (0 =>
array ('id' =>
1, 'name' =>
'Bruce Wayne', 'city' =>
'Gotham', 'gender' =>
'Male', ), 1 =>
array ('id' =>
2, 'name' =>
'Thomas Wayne', 'city' =>
'Gotham', 'gender' =>
'Male', ), ), 'New Mexico' =>
array (0 =>
array ('id' =>
3, 'name' =>
'Diana Prince', 'city' =>
'New Mexico', 'gender' =>
'Female', ), 1 =>
array ('id' =>
4, 'name' =>
'Speedy Gonzales', 'city' =>
'New Mexico', 'gender' =>
'Male', ), ), )
编码愉快!
推荐阅读
- 如何摆脱PHP警告(json_encode()期望参数2长,给定字符串)
- 如何在Symfony 1.4中通过HTTPS(HTTP over SSL)强制全局访问
- Android JobScheduler需要先检查是否正常工作,然后再运行其他任务
- 无法解析Android中的方法'execute()'
- 通过在Android中实现Proguard,使用JDBC在Asynctask中崩溃
- Android Studio - 对象构造函数中的NetworkOnMainThreadException
- 无法将值传递给Android中的AsyncTask
- AsyncTask Android方法的技术差异
- Android AsyncTask问题(连接到Web服务)