您好我遇到了如何在php中按json格式分组的问题。
这是我的代码。
$sql = "SELECT * FROM event as e
JOIN course as c ON e.id = c.event_id
JOIN hold as h ON c.id = h.course_id
GROUP By h.id";
$query = mysqli_query($con, $sql);
$data = [];
while( $row = mysqli_fetch_assoc($query) ) {
$eInfo = new stdClass();
$eInfo->e_info = [];
$event = new stdClass();
$event->e_code = $row['e_code'];
$event->c_info = [];
$course = new stdClass();
$course->c_code = $row['course_code'];
$course->h_info = [];
$hold = new stdClass();
$hold->h_code = $row['hold_code'];
$course->h_info[] = $hold;
$event->c_info[] = $course;
$eInfo->e_info[] = $event;
$data[] = $eInfo;
}
$json = json_encode($data, JSON_PRETTY_PRINT);
return $json
结果是:
[
{
"e_info": [
{
"e_code": "e001",
"c_info": [
{
"c_code": "C001",
"h_info": [
{
"h_code": "h001"
}
]
}
]
}
]
},
{
"e_info": [
{
"e_code": "e001",
"c_info": [
{
"c_code": "C001",
"h_info": [
{
"h_code": "h002"
}
]
}
]
}
]
},
{
"e_info": [
{
"e_code": "e001",
"c_info": [
{
"c_code": "C002",
"h_info": [
{
"h_code": "h001"
}
]
}
]
}
]
},
{
"e_info": [
{
"e_code": "e001",
"c_info": [
{
"c_code": "C002",
"h_info": [
{
"h_code": "h002"
}
]
}
]
}
]
}
]
e_code和course_code是重复的,我想将这些分组。 用php作为json格式可以得到像这样的json数组吗?
[
{
"e_info": [
{
"e_code": "e001",
"c_info": [
{
"c_code": "c001",
"h_info": [
{
"h_code": "h001"
},
{
"h_code": "h002"
}
]
},
{
"c_code": "c002",
"h_info": [
{
"h_code": "h001"
},
{
"h_code": "h002"
}
]
}
]
}
]
}
]
请帮帮我。谢谢。
答案 0 :(得分:0)
您必须在GROUP BY
语句中尝试使用SELECT
"SELECT * FROM tablename GROUP BY e_code, c_code";