Iam目前正在使用PHP从MongoDB中读取数据,如下所示,我的程序中的以下PHP输出需要转换为JSON样式输出,如下所示
Mongo DB PHP输出
数组([_id] => MongoId对象([$ id] => 53481398834269e8e25fa268) [category] => 2014-04-01 [value1] => 400 [value2] => 200)阵列( [_id] => MongoId对象([$ id] => 534813a9834269e8e25fa269) [category] => 2014-04-02 [value1] => 405 [value2] => 205)阵列( [_id] => MongoId对象([$ id] => 534813d7834269e8e25fa26a) [category] => 2014-04-03 [value1] => 408 [value2] => 211)阵列( [_id] => MongoId对象([$ id] => 534813ec834269e8e25fa26b) [category] => 2014-04-04 [value1] => 418 [value2] => 198)阵列( [_id] => MongoId对象([$ id] => 53481402834269e8e25fa26c) [category] => 2014-04-05 [value1] => 370 [value2] => 221)阵列( [_id] => MongoId对象([$ id] => 53481439834269e8e25fa26d) [category] => 2014-04-06 [value1] => 299 [value2] => 180)阵列( [_id] => MongoId对象([$ id] => 5348144e834269e8e25fa26e) [category] => 2014-04-07 [value1] => 311 [value2] => 224)阵列( [_id] => MongoId对象([$ id] => 53481461834269e8e25fa26f) [category] => 2014-04-08 [value1] => 315 [value2] => 254)阵列( [_id] => MongoId对象([$ id] => 5348146f834269e8e25fa270) [category] => 2014-04-09 [value1] => 325 [value2] => 264)阵列( [_id] => MongoId对象([$ id] => 5348147f834269e8e25fa271) [category] => 2014-04-10 [value1] => 335 [value2] => 255)数组( [_id] => MongoId对象([$ id] => 5348148c834269e8e25fa272) [category] => 2014-04-11 [value1] => 365 [value2] => 265)
JSON Style PHP Out
[{" category":" 2013-08-24"," value1":417," value2":127}, { "类别":" 2013-08-25"," value1":417," value2":356},{ "类别":" 2013-08-26"," value1":531," value2":585},{ "类别":" 2013-08-27"," value1":333," value2":910},{ "类别":" 2013-08-28"," value1":552," value2":30},{"类别&#34 ;: " 2013-08-29"," value1":492," value2":371},{" category": " 2013-08-30"," value1":379," value2":781},{" category": " 2013-08-31"," value1":767," value2":494},{" category": " 2013-09-01"," value1":169," value2":364},{" category": " 2013-09-02"," value1":314," value2":476},{" category": " 2013-09-03"," value1":437," value2":759}]
需要专家帮助
答案 0 :(得分:2)
在编码之前,您需要循环遍历数组并以您需要的方式重建它:
$data_to_encode = array();
foreach($mongo_objects as $mongo){
$data['category'] = $mongo['category'];
$data['value1'] = $mongo['value1'];
$data['value2'] = $mongo['value2'];
$data_to_encode[] = $data;
}
$json = json_encode($data_to_encode);
如果您想要更少的变量:
$data = array();
foreach($mongo_objects as $mongo){
$data[] = array('category'=>$mongo['category'],
'value1'=>$mongo['value1'],
'value2'=>$mongo['value2'],
);
}
$json = json_encode($data);
答案 1 :(得分:0)
$json_output = json_encode($MongoDBPHPoutput, true);