PHP 模拟mysql group con_cat最完美的分组方案

<?php

// 封装分组逻辑的函数
function groupBy($array, $key) {
    $result = [];
    foreach ($array as $element) {
        $result[$element[$key]][] = $element;
    }
    $new=[];
foreach($result as $k=>$v){
    $new[$k]['ww']=$v[0];
    $new[$k]['children']=$v;
}
    return $new;
}

// 原始用户数组
$users = [
  ['name' => 'Alice', 'age' => 23, 'email' => 'alice@example.com', 'gender' => 'female'],
  ['name' => 'Bob', 'age' => 30, 'email' => 'bob@example.com', 'gender' => 'male'],
  ['name' => 'Charlie', 'age' => 25, 'email' => 'charlie@example.com', 'gender' => 'male'],
  ['name' => 'David', 'age' => 30, 'email' => 'david@example.com', 'gender' => 'male'],
];

// 按照年龄分组
$groupedUsers = groupBy($users, 'age');


print_r($groupedUsers);
exit();

最完美的分组方案

posted @ 2024-10-16 20:35  newmiracle宇宙  阅读(3)  评论(0编辑  收藏  举报