如何在php中解码json中格式化的数组?

如何在php中解码json中格式化的数组?

问题描述:

I am setting up dialogflow in php to retrieve input from google assistant.

I want to use a parameter I got from dialogflow.

But I don't know how to get it out of the json.

I've already got a function that gets parameters from the json, but it's in a weird format.

How can I get only the pet_name in a variable?

The formats are:

When I use print_r I get:

Array
(
    [pet_name] => gizmo
)

And when I do var_dump I get:

array(1) {
  ["pet_name"]=>
  string(5) "gizmo"
}

Hope this makes it clearer

我在php中设置对话框以检索谷歌助手的输入。 p>

我想使用从dialogflow获得的参数。 p>

但我不知道如何将它从json中删除。 p>

I 已经有了一个从json获取参数的函数,但它的格式很奇怪。 p>

如何在变量中只获取pet_name? p>

格式为: p>

当我使用print_r时,我得到: p>

  Array 
(
 [pet_name] =>  ; gizmo 
)
  code>  pre> 
 
 

当我做var_dump时,我得到: p>

  array(1){\  n [“pet_name”] => 
 string(5)“gizmo”
} 
  code>  pre> 
 
 

希望这会让它更清晰 p>

You can get the name from your index as like:

<?
$string = '{"pet_name":"gizmo"}';
$parsed = json_decode($string);
echo $parsed->pet_name;
?>

if you are using true as a second param in json_decode() then this will return an array and you can get as like:

<?
$string = '{"pet_name":"gizmo"}';
$parsed = json_decode($string,true);
echo $parsed['pet_name'];
?>

You can decode a JSON string using json_decode like so:

<?php

$parsed = json_decode("{\"pet_name\":\"gizmo\"}");

print_r($parsed);

I eventually did

echo $parameters['pet_name'];

And YES it returned 'gizmo!';

Thanks for the help! (I will upvote to thank you for your help.)