本帖最后由 确定过眼神 于 2022-2-8 14:12 编辑
[PHP] 纯文本查看 复制代码 <?php
$arr = [
[
"id" => 199,
"name" => "张三",
"grade" => 1,
"score" => 77,
],
[
"id" => 200,
"name" => "张三",
"grade" => 2,
"score" => 87,
],
[
"id" => 201,
"name" => "李四",
"grade" => 1,
"score" => 78,
],
[
"id" => 202,
"name" => "李四",
"grade" => 2,
"score" => 98,
],
[
"id" => 207,
"name" => "李四",
"grade" => 3,
"score" => 67,
],
];
// 思路
// 重新拼接数组,将每个级别与分数保存到一个数组里面
// 后续直接遍历这个数组即可
$result = [];
foreach ($arr as $index => $item) {
if (isset($result[$item["name"]])) {
// 将级别与分数插入到res数据
array_push($result[$item["name"]]["res"], ["grade" => $item["grade"], "socre" => $item["score"]]);
} else {
// 将姓名也拼接上,方便后续遍历
$result[$item["name"]]["name"] = $item["name"];
// 初始化级别与分数
$result[$item["name"]]["res"][] = ["grade" => $item["grade"], "socre" => $item["score"]];
}
}
// 得到的结果,直接遍历res即可
echo '<pre>';
print_r($result);
echo '</pre>'; |