如何显示特定的 json 值而不是打印或转储函数


How to display specific json values rather than print or dump function

使用以下内容,我可以将所有信息显示为两种格式的数组,但是我希望为变量分配一个值,例如仅使用名称而不是完整的屏幕转储。

$url = 'http://myurl';

$json = file_get_contents($url);

$dump=(var_dump(json_decode($json, true)));

$json_output = json_decode($json); print_r($json_output)

这可能

很容易,我很抱歉。

您可以使用:

$object = json_decode($json);

这将创建一个对象,然后您可以访问这样的属性。

echo $object->whatever;

或者你可以像这样使用json_decode:

$array = json_decode($json, TRUE);

这将创建一个数组,您可以访问类似的个人键。

echo $array['whatever'];

使用 PHP 的 json_decode() 函数应该满足这一点。在第一次调用中,将 TRUE 作为第二个参数传递,因此该函数返回一个关联数组。PHP 手册页说明了这种差异:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

对var_dump的这两个调用将输出:

object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

在以下任一情况下,您都可以访问各个元素:

$json       = '{"url":"stackoverflow.com","rating":"useful"}';
$jsonAsObject   = json_decode($json);
$jsonAsArray    = json_decode($json, TRUE);
echo $jsonAsObject->url . " is " . $jsonAsArray['rating'];

这将输出:

stackoverflow.com is useful

使用面向对象的 dot.notation 来访问变量名称。尝试这样的事情:

alert($json_output->varName);
alert($json_output['varName']);