我有route/json.json返回
[{"titre":"Symfony"},{"titre":"Laravel"},{"titre":"test"}]
,但我只想返回以下值:
["Symfony","Laravel","test"]
这是我的控制器
/**
* @Route("/tags.json", name="liste_tags")
* @param Request $request
* @return SymfonyComponentHttpFoundationJsonResponse
*/
public function index()
{
$tags = $this->getDoctrine()
->getRepository(Tag::class)
->findAll();
return $this->json($tags, 200, [], ['groups' => ['public'] ]);
}
在实体中使用此注释
/**
* @param string $titre
* @Groups({"public"})
* @return Tag
*/
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
您可以使用函数array_column从titre
列
$tags = array_column($tags, 'titre');
如果您确定键始终是 titre ,则可以使用array_map
<?php
//Your JSON, decoded to get an array
$array = json_decode('[{"titre":"Symfony"},{"titre":"Laravel"},{"titre":"test"}]', true);
// Loop over the array to fetch only the value of "titre".
$result = array_map(function($e) {
return $e['titre'];
}, $array);
var_dump($result);
它应该显示:
array(3) {
[0] =>
string(7) "Symfony"
[1] =>
string(7) "Laravel"
[2] =>
string(4) "test"
}