php二维数据某个字段值相同则放到一起,[宜配屋]听图阁
时间: 2023-09-25 10:10:07 浏览: 74
PHP 根据key 给二维数组分组
您可以使用 PHP 中的 array_reduce 函数来实现这个功能。具体步骤如下:
1. 创建一个空数组 $result 以存储结果。
2. 使用 foreach 循环遍历原始数组 $data。
3. 在循环中,检查是否已经存在一个数组键名为当前元素指定字段的值。如果存在,则将当前元素添加到该键名对应的子数组中;否则,在 $result 中创建一个新的子数组,并将当前元素添加到其中。
4. 返回 $result。
以下是示例代码:
```php
function groupByField($data, $field) {
$result = [];
foreach ($data as $item) {
$key = $item[$field];
if (array_key_exists($key, $result)) {
$result[$key][] = $item;
} else {
$result[$key] = [$item];
}
}
return $result;
}
```
假设原始数组 $data 如下所示:
```php
$data = [
["name" => "John", "age" => 20, "city" => "New York"],
["name" => "Alice", "age" => 25, "city" => "Los Angeles"],
["name" => "Bob", "age" => 30, "city" => "New York"],
["name" => "David", "age" => 35, "city" => "San Francisco"],
["name" => "Eve", "age" => 40, "city" => "New York"],
];
```
如果要按照城市将元素分组,可以调用 groupByField($data, "city"),将返回以下结果:
```php
[
"New York" => [
["name" => "John", "age" => 20, "city" => "New York"],
["name" => "Bob", "age" => 30, "city" => "New York"],
["name" => "Eve", "age" => 40, "city" => "New York"],
],
"Los Angeles" => [
["name" => "Alice", "age" => 25, "city" => "Los Angeles"],
],
"San Francisco" => [
["name" => "David", "age" => 35, "city" => "San Francisco"],
],
];
```
阅读全文