【发布时间】:2014-10-22 19:48:11
【问题描述】:
我想创建自定义格式的 JSON 以与 NVD3.js 一起使用,但不确定如何使用 PDO 创建嵌套数组?
示例数据表:
+--------------+-------------------+---------------------+
| volume_name | volume_files_used | recorded |
+--------------+-------------------+---------------------+
| content001 | 130435938 | 2014-08-22 13:20:44 |
| content002 | 95977391 | 2014-08-22 13:20:44 |
+--------------+-------------------+---------------------+
使用PDO 和json_encode():
//JSON OUTPUT
$stmtJSON = $pdo->prepare("SELECT volume_name,
volume_files_used,
recorded FROM collection;");
$stmtJSON->execute();
$json = json_encode($stmtJSON->fetchAll(PDO::FETCH_ASSOC));
print_r($json);
当前JSON 输出:
[
{
"volume_name": "content001",
"volume_files_used": "130435938",
"recorded": "2014-08-22 13:20:44"
},
{
"volume_name": "content002",
"volume_files_used": "95977391",
"recorded": "2014-08-22 13:20:44"
}
]
我想要以下JSON 输出:
[
{
"key": "content001",
"values": [
{
"x": "2014-08-22 13:20:44",
"y": "130435938"
}
]
},
{
"key": "content002",
"values": [
{
"x": "2014-08-22 13:20:44",
"y": "95977391"
}
]
}
]
在上面的示例中只有两行,但实际上我想将每个volume_name 的所有values 提取为key:
[
{
"key": "content001",
"values": [
{
"x": "2014-08-22 13:20:44",
"y": "130435938"
},
{
"x": "2014-08-22 14:20:44",
"y": "130435940"
},
{
"x": "2014-08-22 15:20:44",
"y": "130435945"
},
{
"x": "2014-08-22 16:20:44",
"y": "130435965"
}
]
},
{
"key": "content002",
"values": [
{
"x": "2014-08-22 13:20:44",
"y": "95977391"
},
{
"x": "2014-08-22 14:20:44",
"y": "95977402"
},
{
"x": "2014-08-22 15:20:44",
"y": "95977445"
},
{
"x": "2014-08-22 16:20:44",
"y": "95977457"
}
]
}
]
回答更新
Charlotte Dunois更新输出:
{
"content002": {
"values": [
{
"y": "95583732",
"x": "2014-08-27 11:05:01"
},
{
"y": "95539534",
"x": "2014-08-27 12:05:01"
}
],
"key": "content002"
},
"content001": {
"values": [
{
"y": "130121075",
"x": "2014-08-27 11:05:01"
},
{
"y": "130131806",
"x": "2014-08-27 12:05:01"
}
],
"key": "content001"
}
}
工作答案
我设法从另一个开发人员那里获得了帮助。下面的代码是有效的,但如果你能做得更好,任何人都可以发表评论。
//JSON OUTPUT
$stmtJSON = $pdo->prepare("SELECT volume_name,
volume_files_used,
recorded FROM collection;");
$stmtJSON->execute();
$result = $stmtJSON->fetchAll(PDO::FETCH_ASSOC));
$temp_array = array();
foreach($result as $bf) {
if (!isset($temp_array[$bf['volume_name']])) {
$temp_array[$bf['volume_name']] = array();
}
$temp_array[$bf['volume_name']][] = array(
"x" => $bf['recorded'],
"y" => $bf['volume_files_used']);
}
$final_array = array();
foreach ($temp_array as $volume_name => $values) {
$final_array[] = array(
'key' => $volume_name,
'values' => $values);
}
$json = json_encode($final_array);
【问题讨论】:
标签: php mysql json pdo nvd3.js