[英]convert object to json data from sql
我想將數據對象轉換為json形式,這是我在symfony中的代碼,
$connection = $em->getConnection();
$statement = $connection->prepare("select * from contact where id_user=$id");
$statement->execute();
$contacts = $statement->fetchAll();
在渲染對象時,我這樣做
return $this->render('...index.html.twig', array('form' => $form->createView(), 'errors' => $form->getErrors(), 'contacts'=>json_encode($contacts)));
但這不起作用,請提供任何幫助
嘗試這個:
$contacts= json_encode($contacts);
$Response = new Response(
'...myTemplate.html.twig',
['form' => $form->createView()],
['errors' => $form->getErrors()],
['contacts' => $contacts]
);
$Response->headers->set('Content-Type', 'application/json');
return $oResponse;
不要忘記使用:
use Symfony\Component\HttpFoundation\Response;
或者,您可以使用JsonResponse類。 這是文檔: symfony doc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.