如何将对象转换为数组(Symfony)



这就是我创建数组fields:的方式

public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$page = $this->getDoctrine()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
$fields =  (array) $page;
return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
}

输出为:

array:3 [▼
"x00AppEntityPagesx00id" => 3
"x00AppEntityPagesx00name" => "cat"
"x00AppEntityPagesx00color" => ""
]

但我实际上需要这个结果:

array:3 [▼
"id" => 3
"name" => "cat"
"color" => ""
]

根据我的建议,我做出了这个改变:

public function index($slug, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$page = $this->getDoctrine()->getManager()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
$fields =  get_object_vars($page);
return $this->render('mypage.html.twig', ['page' => $page, 'fields' => $fields]);
}

但这会输出一个空数组。

您有两个选项:

1.使用Query::HYDRATE_ARRAY而不是findOneBy()

$query = $this->getDoctrine()
->getRepository(Pages:class)
->createQueryBuilder('p')
->getQuery();
$result = $query->getResult(Query::HYDRATE_ARRAY);

(此答案被盗(

2.使用序列化程序

使用Serializer组件或JMSSerializerBundle序列化实体对象。

相关内容

  • 没有找到相关文章

最新更新