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

时间:2018-11-26 08:20:45

标签: arrays symfony oop object

这就是我创建数组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 [▼
  "\x00App\Entity\Pages\x00id" => 3
  "\x00App\Entity\Pages\x00name" => "cat"
  "\x00App\Entity\Pages\x00color" => ""
]

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

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 个答案:

答案 0 :(得分:3)

您有两个选择:

1。使用Query::HYDRATE_ARRAY 代替findOneBy()

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

(从this answer窃取)

2。使用序列化器

使用Serializer ComponentJMSSerializerBundle序列化您的实体对象。