在PHP中,递归地对多个键上的数组进行分组可以通过以下步骤实现:
以下是一个示例代码:
function groupArrayByKeys($array, $keys) {
if (empty($array)) {
return [];
}
$currentKey = array_shift($keys);
$groups = [];
foreach ($array as $item) {
$key = $item[$currentKey];
if (!isset($groups[$key])) {
$groups[$key] = [];
}
$groups[$key][] = $item;
}
if (!empty($keys)) {
foreach ($groups as $key => $group) {
$groups[$key] = groupArrayByKeys($group, $keys);
}
}
return $groups;
}
// 示例用法
$data = [
['id' => 1, 'category' => 'fruit', 'name' => 'apple'],
['id' => 2, 'category' => 'fruit', 'name' => 'orange'],
['id' => 3, 'category' => 'vegetable', 'name' => 'carrot'],
['id' => 4, 'category' => 'vegetable', 'name' => 'cabbage'],
['id' => 5, 'category' => 'fruit', 'name' => 'banana'],
['id' => 6, 'category' => 'vegetable', 'name' => 'tomato'],
];
$keys = ['category', 'name'];
$result = groupArrayByKeys($data, $keys);
print_r($result);
上述代码将根据category
和name
两个键对数组进行分组。输出结果如下:
Array
(
[fruit] => Array
(
[apple] => Array
(
[0] => Array
(
[id] => 1
[category] => fruit
[name] => apple
)
)
[orange] => Array
(
[0] => Array
(
[id] => 2
[category] => fruit
[name] => orange
)
)
[banana] => Array
(
[0] => Array
(
[id] => 5
[category] => fruit
[name] => banana
)
)
)
[vegetable] => Array
(
[carrot] => Array
(
[0] => Array
(
[id] => 3
[category] => vegetable
[name] => carrot
)
)
[cabbage] => Array
(
[0] => Array
(
[id] => 4
[category] => vegetable
[name] => cabbage
)
)
[tomato] => Array
(
[0] => Array
(
[id] => 6
[category] => vegetable
[name] => tomato
)
)
)
)
在这个示例中,我们根据category
键和name
键对数组进行了分组,最终得到了按照category
和name
进行嵌套分组的结果。这个方法可以用于对多个键上的数组进行任意深度的递归分组。
腾讯云相关产品和产品介绍链接地址:
请注意,上述链接仅为腾讯云产品的示例,其他云计算品牌商也提供类似的产品和服务。
领取专属 10元无门槛券
手把手带您无忧上云