我需要从JSON中获取密钥字符串



我在一个laravel API请求中有这个JSON:

{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14 
}

我需要获得字符串";directLeader导致请求中的这个键发生了更改,我将其用作查询更新的参考。

  • 要将json转换为数组:

$array=json_decode($json,true(;

  • 要获取关联数组中的第一个键:

$firstKey=array_key_first($array['questionary'](;

$firstKey将包含您的动态密钥。

您需要json_decode()您喜欢的json,这样

$json = '{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14 
}';
$encoded_json = json_decode($json, true);
dd($encoded_json['questionary']['directLeader']);

注意json_decode()中的true将把对象转换为数组,如果没有true,它将成为对象

最新更新