php 二维数组如何对指定多个字段进行分组
方法1:
function group_by_multiple_keys($array, $keys)
{
$result = [];
foreach ($array as $item) {
// 从第一个键开始
$current_level = &$result;
foreach ($keys as $key) {
// 如果当前键不存在,则创建一个空数组
if (!isset($current_level[$item[$key]])) {
$current_level[$item[$key]] = [];
}
// 移动到下一个嵌套级别
$current_level = &$current_level[$item[$key]];
}
// 到达最后一个键,将原始项添加到数组中
$current_level[] = $item;
}
return $result;
}
方法2:
function group_by_multiple_keys($array, $keys)
{
$result = [];
foreach ($array as $item) {
$groupKey = [];
foreach ($keys as $key) {
$groupKey[] = $item[$key];
}
$groupKey = implode('-', $groupKey);
$result[$groupKey][] = $item;
}
$grouped = [];
foreach ($result as $key => $group) {
$keys = explode('-', $key);
$grouped[$keys[0]][$keys[1]] = $group;
}
return $grouped;
}
方法3:
function group_by_multiple_keys($array, $keys)
{
$reduced = array_reduce($array, function ($carry, $item) use ($keys) {
$carryKey = [];
foreach ($keys as $key) {
$carryKey[] = $item[$key];
}
$carryKey = implode('-', $carryKey);
$carry[$carryKey][] = $item;
return $carry;
}, []);
uksort($reduced, function ($a, $b) use ($keys) {
$aParts = explode('-', $a);
$bParts = explode('-', $b);
foreach ($keys as $index => $key) {
if ($aParts[$index] === $bParts[$index]) continue;
return $aParts[$index] <=> $bParts[$index];
}
return 0;
});
$grouped = [];
foreach ($reduced as $key => $group) {
$keys = explode('-', $key);
$grouped[$keys[0]][$keys[1]] = $group;
}
return $grouped;
}
本文来自博客园,作者:Carvers,转载请注明原文链接:https://www.cnblogs.com/carver/articles/18582779

浙公网安备 33010602011771号