php数组group by
时间: 2023-07-27 10:07:09 浏览: 181
PHP中的数组
在 PHP 中,可以使用 array_reduce() 函数来实现类似于 SQL 的 GROUP BY 功能,以下是一个示例代码:
```php
<?php
$data = array(
array('name' => 'John', 'age' => 25, 'gender' => 'male'),
array('name' => 'Jane', 'age' => 22, 'gender' => 'female'),
array('name' => 'Bob', 'age' => 30, 'gender' => 'male'),
array('name' => 'Alice', 'age' => 28, 'gender' => 'female'),
array('name' => 'Tom', 'age' => 25, 'gender' => 'male')
);
$grouped = array_reduce($data, function($result, $item) {
$key = $item['age'];
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key][] = $item;
return $result;
}, array());
print_r($grouped);
?>
```
上述代码将按照年龄将数组 $data 中的元素进行分组,输出结果如下:
```
Array
(
[25] => Array
(
[0] => Array
(
[name] => John
[age] => 25
[gender] => male
)
[1] => Array
(
[name] => Tom
[age] => 25
[gender] => male
)
)
[22] => Array
(
[0] => Array
(
[name] => Jane
[age] => 22
[gender] => female
)
)
[30] => Array
(
[0] => Array
(
[name] => Bob
[age] => 30
[gender] => male
)
)
[28] => Array
(
[0] => Array
(
[name] => Alice
[age] => 28
[gender] => female
)
)
)
```
可以看到,输出结果是一个关联数组,其中键值为分组的依据(这里是年龄),对应的值为分组后的元素数组。
阅读全文