我已经完成了一个查询,要求从其他表中获取相同ID的所有数据。在同一个ID下有超过2个数据。
我需要像数组一样在同一个id下显示所有数据。
这是我的SQL查询:
"SELECT incident.*,entry.*,fighter.*
FROM register_incident AS incident JOIN
register_entry_points AS entry
ON entry.incident_id = incident.incident_id
JOIN add_fire_fighters AS fighter
ON entry.entrypoint_id = fighter.entry_point_id
WHERE incident.incident_id=:incident_id"
我得到了一个回复,
"data":[
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"incident_id": "5",
"user_id": "16",
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": "300",
"time_in": "10:30:00",
"time_out": "11:45:00",
"duration": "01:15",
"notes": "Test"
},
但我需要显示它,
"data": [
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter":{
{
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
}
}
}]
怎么可能?
答案 0 :(得分:0)
如果我从具有一个或多个1:n关系的Query中获取ResultSet,我会像这样的样本一样得到结果。
$Result = array();
foreach($Records as $Record) {
// key 1
$key1 = $Record['incident_id'];
if(isset($Result[$key1])) {
$cuIncident=$Result[$key1];
}
else {
$cuIncident=array(
'incident_id' => $key1,
'user_id' => $Record['user_id'],
//......
'fighter' => array()
);
$Result[$key1] = $cuIncident;
}
// key 2
$key2 = $Record['fighter_id'];
if(isset($cuIncident['fighter'][$key2])) {
$cuFighter = $cuIncident['fighter'][$key2];
}
else {
$cuFighter = array(
'fighter_id' => $key2,
'entry_point_id' => $Record['entry_point_id'],
//......
'key3array' => array()
);
$cuIncident['fighter'][$key2] = $cuFighter;
}
// key 3
// ....
如果某个键是多值键,则必须组合这些键,如:
$key3 = $Record['key3prop1']."/".$Record['key3prop2'];
if(isset($key3Array[$key3])) ......