我在这里看到了很多类似的问题,但是我无法得到我想要的输出。有人可以帮帮我吗?如何生成以下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);
}
}
注意:每个玩家可以拥有多个“统计”记录(年,小时,rbi等)
答案 0 :(得分:3)
这可能会给你想要的东西:
$players = array();
while ($row = $result->fetch_assoc())
{
$id = (int)$row['cbs_id'];
if ( ! isset($players[$id]))
{
// New player, add to $players array.
// For the moment index players by ID so stats can be easily added
// to an existing player. Without indexing (using $players[] = ...),
// the same player would be added for each stats record related to
// him.
$players[$id] = array(
'id' => $id,
'fname' => $row['fname'],
'lname' => $row['lname'],
'stats' => array()
);
}
// Add the stats
$players[$id]['stats'][] = array(
'year' => (int)$row['year'],
'hr' => (int)$row['hr'],
'rbi' => (int)$row['rbi']
);
}
// Players are indexed by their ID in $players but need to be contained in
// a JSON array, so use array_values() to remove indices, e.g. convert
//
// array(
// 271 => array('id' => 271, ...),
// ...
// )
//
// to
//
// array(
// array('id' => 271, ...),
// ...
// )
//
$data = array('players' => array_values($players));
$json = json_encode($data);
最终你可能会遗漏整数强制转换并让PHP使用 MYSQLI_OPT_INT_AND_FLOAT_NATIVE mysqli连接选项自动将字符串化的数字数据(这是MySQL查询结果的默认行为)转换回PHP数字,如this page的示例#5。请注意,它需要PHP使用mysqlnd库(您可以使用phpinfo
进行检查。)
答案 1 :(得分:2)
您需要一个关联数组。这样的事情会让你开始:
$data = array(
'players' => array(
array(
'id' => 271,
'fname': 'Carlos',
'lname': 'Beltran',
'position': 'OF',
'stats' => array(
array(
'year' => 2010,
'hr': 32,
'rbi': 99,
'team': 'NYM'
),
...
)
),
...
)
);
要将其编码为json,请使用json_encode:
$json = json_encode($data);