我只想从嵌套数组中获取第一个“ firstPerson”参数

时间:2019-04-04 17:20:08

标签: php

我只想显示此数组参数“ firstPerson”的json_encode。

$someArray = [
    "firstPerson" => [
      "name"   => "Jonathan",
      "gender" => "male"
    ],
    "secondPerson" => [
      "name"   => "William",
      "gender" => "male"
    ],
    "thirdPerson" => [
      "name"   => "Allison",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
$someJSON = json_encode($someArray);
  echo $someJSON;

1 个答案:

答案 0 :(得分:0)

您可以获取第一个元素,然后将其编码为json:

$someJSON = json_encode($someArray['firstPerson']);
echo $someJSON; 
// output :
// {"name":"Jonathan","gender":"male"}