Reputation: 388
I have Route /json.json return
[{"titre":"Symfony"},{"titre":"Laravel"},{"titre":"test"}]
But I want to return only values like :
["Symfony","Laravel","test"]
This is my controller
/**
* @Route("/tags.json", name="liste_tags")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function index()
{
$tags = $this->getDoctrine()
->getRepository(Tag::class)
->findAll();
return $this->json($tags, 200, [], ['groups' => ['public'] ]);
}
With this annotation in entity
/**
* @param string $titre
* @Groups({"public"})
* @return Tag
*/
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
Upvotes: 0
Views: 560
Reputation: 1755
You can use the function array_column to get the values from the titre
column
$tags = array_column($tags, 'titre');
Upvotes: 4
Reputation: 2132
If you are sure the keys will always be titre, you can use 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);
It should show:
array(3) {
[0] =>
string(7) "Symfony"
[1] =>
string(7) "Laravel"
[2] =>
string(4) "test"
}
Upvotes: 0