我想获得以下json:
{
"1": {
"A1": {
"drink": "Beer",
"volume": "0.0965"
},
"A2": {
"drink": "Beer",
"volume": "0.1029"
}
}, // etc.
我的php是:
$sql = "SELECT keg_no, sub_no, drink, volume FROM keg ORDER BY keg_no, sub_no, drink, volume;";
$query = $db->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$rows = array();
foreach ($results as $row)
$rows[$row['keg_no']][$row['sub_no']] [] = [drink=>$row['drink'], volume=>$row['volume']];
$json = json_encode($rows);
echo $json;
我的javascript是:
function getKegs () {
$.post('getKegs.php', {}, function(data) {
if (data) {
keg = $.parseJSON(data);
} else
alert('No reply from database');
});
}
上述结果在方括号中产生了不必要的尺寸:
{
"1": {
"A1": [{
"drink": "Beer",
"volume": "0.0965"
}],
"A2": [{
"drink": "Beer",
"volume": "0.1029"
}], // etc.
方括号可以使用str_replace(php)/ replace(js)删除,我仍然可以获得有效的json而没有不必要的维度,但是理解为什么/如何添加方括号以及它们如何能够更加令人满意被删除。