我在这里看到了很多类似的问题,但我无法获得我想要的输出。有人可以帮我吗?如何生成以下 JSON 结构?我的查询很好,我只是不知道如何循环并得到它。谢谢
期望的输出
{
"players": [
{
"id": 271,
"fname": "Carlos",
"lname": "Beltran",
"position": "OF",
"stats": [
{
"year": "2010",
"hr": 32,
"rbi": 99,
"team": "NYM"
},
{
"year": "2011",
"hr": 35,
"rbi": 100,
"team": "STL"
},
{
............
}
]
},
{
........
}
]
}
电流输出
{"0":{"cbs_id":"18817","fname":"Carlos","lname":"Beltran"},"stats":[{"year":"2007","hr":"33","rbi":"112"}]}
{"0":{"cbs_id":"174661","fname":"Willie","lname":"Bloomquist"},"stats":[{"year":"2007","hr":"2","rbi":"13"}]}
{"0":{"cbs_id":"1208693","fname":"Brennan","lname":"Boesch"},"stats":[{"year":"2010","hr":"14","rbi":"67"}]}
生成的是:(我知道我很遥远)
if ($result = mysqli_query($link, $sql)) {
$player = array();
while ($row = $result->fetch_assoc())
{
$player[] = array (
'cbs_id' => $row['cbs_id'],
'fname' => $row['fname'],
'lname' => $row['lname']
);
$player['stats'][] = array(
'year' => $row['year'],
'hr' => $row['hr'],
'rbi' => $row['rbi']
);
}
$json = json_encode($player);
echo "<pre>$json</pre>";
mysqli_free_result($result);
}
}
注意:每个玩家可以有多个“统计”记录(年、小时、打点等)