可以使用PHP中的array_reduce函数和array_push函数来实现。下面是示例代码:
function groupRecordsByElement($records, $element) {
$result = array_reduce($records, function($carry, $record) use ($element) {
$key = $record[$element];
if (!array_key_exists($key, $carry)) {
$carry[$key] = array();
}
array_push($carry[$key], $record);
return $carry;
}, array());
return $result;
}
// 示例数据
$records = array(
array("id" => 1, "name" => "Alice", "group" => "A"),
array("id" => 2, "name" => "Bob", "group" => "B"),
array("id" => 3, "name" => "Charlie", "group" => "A"),
array("id" => 4, "name" => "David", "group" => "B"),
array("id" => 5, "name" => "Eve", "group" => "C")
);
// 按照"group"元素对记录进行分组
$groupedRecords = groupRecordsByElement($records, "group");
print_r($groupedRecords);
输出结果如下:
Array
(
[A] => Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[group] => A
)
[1] => Array
(
[id] => 3
[name] => Charlie
[group] => A
)
)
[B] => Array
(
[0] => Array
(
[id] => 2
[name] => Bob
[group] => B
)
[1] => Array
(
[id] => 4
[name] => David
[group] => B
)
)
[C] => Array
(
[0] => Array
(
[id] => 5
[name] => Eve
[group] => C
)
)
)
这段代码将示例数据按照"group"元素的值进行分组,返回一个新的数组。每个分组的值作为键,对应的记录数组作为值。可以看到,记录被正确地按照"group"元素进行了分组。
领取专属 10元无门槛券
手把手带您无忧上云