Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用FOSRestBundle(对象数组)返回正确的JSON_Php_Json_Fosrestbundle - Fatal编程技术网

Php 使用FOSRestBundle(对象数组)返回正确的JSON

Php 使用FOSRestBundle(对象数组)返回正确的JSON,php,json,fosrestbundle,Php,Json,Fosrestbundle,我有一个POST action,如下所示: public function cpostAction(Request $request) { $records = json_decode($request->getContent(), true); $arr = array(); $em = $this->getDoctrine()->getManager(); foreach((array)$records as $record) {

我有一个POST action,如下所示:

public function cpostAction(Request $request)
{
    $records = json_decode($request->getContent(), true);
    $arr = array();
    $em = $this->getDoctrine()->getManager();
    foreach((array)$records as $record) {
        $obj = new \stdClass();
        $entity = new Record();
        $entity->setRouteId($record['routeId']);
        $entity->setDate(new \DateTime('now'));
        $entity->setUserId($record['userId']);
        $entity->setSync($record['sync']);
        $obj->id = $record['id'];
        $em->persist($entity);
        $em->flush();
        $obj->remote_id = $entity->getId();
        $obj = json_encode($obj, true);
        array_push($arr, $obj);
    }

    $view = View::create();
    $view->setFormat('json');
    $view->setData($arr);
    return $this->get('fos_rest.view_handler')->handle($view);
}
如果我保留
$obj=json\u encode($obj,true),我得到了这个响应

[
    "{\"id\":1,\"remote_id\":52}",
    "{\"id\":2,\"remote_id\":53}",
    "{\"id\":3,\"remote_id\":54}"
]
如果没有这行代码,我会

{
    "0": {},
    "1": {},
    "2": {}
}

如何获取正确的JSON?

如果使用数组而不是stdClass
,会怎么样?序列化程序只是不知道如何序列化给定的objects@zerkms:那很好用,谢谢!