实现根据数组的值进行分组的方法,可以借助PHP自带的函数array_reduce()和array_merge()。具体步骤如下:
实现根据数组的值进行分组的方法,可以借助PHP自带的函数array_reduce()和array_merge()。具体步骤如下:
- 定义初始结果数组
通过array_reduce()函数对数组进行遍历,将结果放入一个初始化的空数组中。
$groups = array_reduce($arr, function($result, $item) {
...
return $result;
}, array());
- 判断值是否已有分组
在循环中,通过判断当前值是否已经有分组来决定将其添加到已有分组中,还是创建新的分组。
$groups = array_reduce($arr, function($result, $item) {
$grouped = false;
foreach ($result as $key => $group) {
if ($item['group'] == $key) {
$result[$key][] = $item;
$grouped = true;
break;
}
}
if (!$grouped) {
$result[$item['group']] = array($item);
}
return $result;
}, array());
- 返回分组后的结果
最后,通过返回结果数组$groups来获取分组后的数组数据。
完整代码示例1:
<?php
$arr = array(
array('name' => 'apple','group' => 'fruit'),
array('name' => 'pear','group' => 'fruit'),
array('name' => 'carrot','group' => 'vegetable'),
array('name' => 'onion','group' => 'vegetable'),
array('name' => 'beef','group' => 'meat'),
);
$groups = array_reduce($arr, function($result, $item) {
$grouped = false;
foreach ($result as $key => $group) {
if ($item['group'] == $key) {
$result[$key][] = $item;
$grouped = true;
break;
}
}
if (!$grouped) {
$result[$item['group']] = array($item);
}
return $result;
}, array());
print_r($groups);
?>
输出结果:
Array
(
[fruit] => Array
(
[0] => Array
(
[name] => apple
[group] => fruit
)
[1] => Array
(
[name] => pear
[group] => fruit
)
)
[vegetable] => Array
(
[0] => Array
(
[name] => carrot
[group] => vegetable
)
[1] => Array
(
[name] => onion
[group] => vegetable
)
)
[meat] => Array
(
[0] => Array
(
[name] => beef
[group] => meat
)
)
)
完整代码示例2:
<?php
$arr = array(
array('name' => 'John','age' => 25,'gender' => 'male'),
array('name' => 'Mark','age' => 30,'gender' => 'male'),
array('name' => 'Jenny','age' => 22,'gender' => 'female'),
array('name' => 'Amy','age' => 26,'gender' => 'female'),
array('name' => 'David','age' => 19,'gender' => 'male'),
);
$groups = array_reduce($arr, function($result, $item) {
$grouped = false;
foreach ($result as $key => $group) {
if ($item['gender'] == $key) {
$result[$key][] = $item;
$grouped = true;
break;
}
}
if (!$grouped) {
$result[$item['gender']] = array($item);
}
return $result;
}, array());
print_r($groups);
?>
输出结果:
Array
(
[male] => Array
(
[0] => Array
(
[name] => John
[age] => 25
[gender] => male
)
[1] => Array
(
[name] => Mark
[age] => 30
[gender] => male
)
[2] => Array
(
[name] => David
[age] => 19
[gender] => male
)
)
[female] => Array
(
[0] => Array
(
[name] => Jenny
[age] => 22
[gender] => female
)
[1] => Array
(
[name] => Amy
[age] => 26
[gender] => female
)
)
)
沃梦达教程
本文标题为:PHP实现根据数组的值进行分组的方法
基础教程推荐
猜你喜欢
- php 删除数组元素 2024-01-14
- PHP递归实现快速排序的方法示例 2022-10-02
- Yii redis集合的基本使用教程 2023-04-20
- Laravel框架FormRequest中重写错误处理的方法 2022-12-20
- PHP实现动态压缩js与css文件的方法 2022-10-15
- laravel添加角色和模糊搜索功能的实现代码 2023-06-12
- laravel下trait的使用代码实例详解 2023-05-20
- PHP单例模式实例分析【防继承,防克隆操作】 2023-01-15
- PHP的new static和new self的区别与使用 2023-03-17
- PHP面向对象程序设计之多态性的应用示例 2022-11-28