我想创建与NVD3.js一起使用的自定义格式化JSON,但我不确定如何使用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"
}
]
}
]
在上面的示例中,只有两行,但实际上我想将每个values
的所有volume_name
拉为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"
}
}
<小时/>
我设法得到了另一个Dev的帮助。以下代码正常运行,但如果您能做得更好,任何人都可以发表评论。
//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);
答案 0 :(得分:2)
在将其编码为json对象之前,必须使用此结构创建一个新数组。这样做(你的新格式化数组在$ new_array中,所以你可以只对json进行编码):
$new_array = array();
foreach($pdo_response as $bf) {
if(empty($new_array[$bf['volume_name']])) {
$new_array[$bf['volume_name']] = array("key" => $bf['volume_name'], "values" => array());
}
$new_array[$bf['volume_name']]['values'][] = array("x" => $bf['recoreded'], "y" => $bf['volume_files_used']);
}
如果你想要第一个维度的数字键(0 - ....),请使用array_values()。