Group subarrays by one column, make comma-separated values from other column within groups(按一列对子数组进行分组,从组内的其他列生成逗号分隔的值)
问题描述
我有一个看起来像这样的数组:
I have a array that looks like this:
$array = [
["444", "0081"],
["449", "0081"],
["451", "0081"],
["455", "2100"],
["469", "2100"]
];
我需要分组为一个新数组,如下所示:
I need to group as a new array that looks like:
array (
0 =>
array (
0 => '444,449,451',
1 => '0081',
),
1 =>
array (
0 => '455,469',
1 => '2100',
),
)
我尝试了很多脚本,但都没有成功.
I'd tried many scripts, but with no success.
function _group_by($array, $key) {
$return = array();
foreach($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
$newArray = _group_by($array, 1); // (NO SUCCESS)
推荐答案
应该有更优雅的解决方案,但我能想到的最简单的就是这个.
There should be more elegant solutions, but simplest one I can think of would be this.
// The data you have pasted in the question
$data = [];
$groups = [];
// Go through the entire array $data
foreach($data as $item){
// If the key doesn't exist in the new array yet, add it
if(!array_key_exists($item[1], $groups)){
$groups[$item[1]] = [];
}
// Add the value to the array
$groups[$item[1]][] = $item[0];
}
// Create an array for the data with the structure you requested
$structured = [];
foreach($groups as $group => $values){
// With the array built in the last loop, implode it with a comma
// Also add the 'key' from the last array to it ($group)
$structured[] = [implode(',', $values), $group];
}
我还没有测试过这个,但类似的东西应该可以解决问题.这只是通过给定的数组并以结构化的方式收集所有条目(因此 $groups
变量将包含每个共享密钥的组的数组条目,并且该密钥将对应于每个给定数组中的项目).从那里开始,它只是重组它以获得您要求的格式.
I haven't tested this but something similar should do the trick. This simply goes through the given array and collects all entries in a structurized manner (so $groups
variable will contain an array entry for each group sharing a key, and the key will correspond to the 2nd item in each item within the given array). From there it's just about restructuring it to get the format you have requested.
http://php.net/manual/en/control-structures.foreach.php
这篇关于按一列对子数组进行分组,从组内的其他列生成逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按一列对子数组进行分组,从组内的其他列生成
基础教程推荐
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01