【问题标题】:How to return json without its key如何在没有密钥的情况下返回 json
【发布时间】:2019-03-15 10:07:29
【问题描述】:

我有路线 /json.json 返回

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

但我只想返回如下值:

["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;
}

【问题讨论】:

  • $tags 的输出是什么?
  • [{"id":"1","titre":"Symfony"}]
  • 嗨@Khalil,如果有任何答案解决了您的问题,请点击复选标记考虑accepting it

标签: php arrays json symfony symfony4


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您确定密钥总是tire,您可以使用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"
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多