如何在没有密钥的情况下 return json

How to return json without its key

我有路线 /json.json return

[{"titre":"Symfony"},{"titre":"Laravel"},{"titre":"test"}]

但我只想 return 值,例如:

["Symfony","Laravel","test"]

这是我的控制器

   /**
     * @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'] ]);
    }

在实体中使用此注释

/**
 * @param string $titre
 * @Groups({"public"})
 * @return Tag
 */
public function setTitre(string $titre): self
{
    $this->titre = $titre;

    return $this;
}

如果您确定密钥将始终是 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"
}

您可以使用函数 array_columntitre 列中获取值

$tags = array_column($tags, 'titre');