我使用mongo odm查询来获取数据但是当我获得查询数据时它以数组格式返回但我想获取json格式的数据如何将数据从数组转换为json?这是我的代码:
public function loadAction()
{
$response = $this->getResponse();
$id = (int) $this->params()->fromRoute('id', 0);
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendars = $dm->createQueryBuilder('Calendar\Document\Event')
->hydrate(false)
->field("calendar_id")->equals($id)
->getQuery()->execute();
$array = array();
if($calendars && !is_null($calendars) && is_object($calendars)){
foreach($calendars as $key=>$value) {
$array[] = $value;
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
return $response;
//return $this->getResponse()->setContent(Json::encode($array));
}
以下是我的回复:
Array
(
[0] => Array
(
[_id] => 11
[calendar_id] => 44
[title] => fhfhfhfhfhfhfhf
[description] => hfhfhfhfhffh
[begin] => MongoDate Object
(
[sec] => 1397744580
[usec] => 0
)
[end] => MongoDate Object
(
[sec] => 1403187780
[usec] => 0
)
)
[1] => Array
(
[_id] => 12
[calendar_id] => 44
[title] => fhfhfhfhfhfhfhfdgdg
[description] => hfhfhfhfhffhdgdgdg
[begin] => MongoDate Object
(
[sec] => 1397744580
[usec] => 0
)
[end] => MongoDate Object
(
[sec] => 1403360580
[usec] => 0
)
)
[2] => Array
(
[_id] => 13
[calendar_id] => 44
[title] => xvxvxvxv
[description] => czzzvxvvzxvxvzxv
[begin] => MongoDate Object
(
[sec] => 1398349380
[usec] => 0
)
[end] => MongoDate Object
(
[sec] => 1403706180
[usec] => 0
)
)
[3] => Array
(
[_id] => 14
[calendar_id] => 44
[title] => xvxvxvxggjgjfj
[description] => czzzvxvvzxhhdfhhd
[begin] => MongoDate Object
(
[sec] => 1398349380
[usec] => 0
)
[end] => MongoDate Object
(
[sec] => 1403706180
[usec] => 0
)
)
[4] => Array
(
[_id] => 15
[calendar_id] => 44
[title] => xvxvxvxggjgjfjsadgggggggfdhdfhhdh
[description] => czzzvxvvzxhhdfhhddghhffffffffffffff
[begin] => MongoDate Object
(
[sec] => 1398349380
[usec] => 0
)
[end] => MongoDate Object
(
[sec] => 1404138180
[usec] => 0
)
)
)
但我想要这种格式的数据:
[{
"event_id":"2",
"calendar_id":"1",
"author_id":"1",
"title":"Launch",
"description":"Launch Break",
"begin":"2014-03-02 20:00:00",
"end":"2014-03-31 16:53:00",
"calendar_title":"Hijri Calender",
"author_email":"arif.liaqat@yahoo.com"
}]
答案 0 :(得分:2)
您可以使用php本机功能 json_encode 和 json_decode 来获取并将变量置于特定格式
答案 1 :(得分:1)
if($calendars && !is_null($calendars) && is_object($calendars)){
foreach($calendars as $key => $value) {
$array[] = array(
'event_id' => $value['_id'],
'calendar_id' => $value['calendar_id'],
'author_id' => $value['author_id'], // <-- author_id is defined?
'title' => $value['title'],
'description' => $value['description'],
'begin' => date('Y-m-d H:i:s', $value['begin']->sec),
'end' => date('Y-m-d H:i:s', $value['end']->sec),
'calendar_title' => $value['calendar_title'], // <-- calendar_title is defined?
'etc..' => $value['etc..'],
);
}
}
答案 2 :(得分:0)
然后你可以通过JsonModel返回它(如前面提到的JsonModel将对数组进行编码!!):
return new JsonModel(array(
'array' => $array
));
不要忘记将JsonModel包含在您的文件之上:
use Zend\View\Model\JsonModel;