如何引用数组中的数据(php/json)
我使用以下方法获取json对象:如何引用数组中的数据(php/json),php,arrays,json,Php,Arrays,Json,我使用以下方法获取json对象: $json = file_get_contents("url-here"); $data = json_decode($json, true); //test var_dump($data); 这给了我这样的东西: 数组(2){[“确定”]=>bool(真)[“结果”]=>array(1){[0]=>array(2) {[“update_id”]=>int(44893465)[“message”]=>array(5){ [“message_id”]=>int(
$json = file_get_contents("url-here");
$data = json_decode($json, true);
//test
var_dump($data);
这给了我这样的东西:
数组(2){[“确定”]=>bool(真)[“结果”]=>array(1){[0]=>array(2)
{[“update_id”]=>int(44893465)[“message”]=>array(5){
[“message_id”]=>int(16)[“from”]=>array(3){[“id”]=>int(29595794)
[“名字”]=>string(3)“Bob”[“用户名”]=>string(14)“Bobo”}
[“chat”]=>array(3){[“id”]=>int(29595794)[“first_name”]=>
字符串(3)“Bob”[“username”]=>字符串(14)“Bobo”}[“date”]=>
int(1435354253)[“text”]=>string(7)“/q3.33”}
然后我想将某些值添加到变量中。例如,我想提取用户名、文本、消息id等
但无论我尝试什么,我的变量都是空的:
//let's test it
echo "Username: " . $data[1][0]["username"];
//another test
echo $data->username;
这两种方法都不起作用,我的研究也没有帮助我找到解决办法。我在这件事上被难住了
任何指向正确方向的指示都将非常感激
array(2) {
["ok"]=> bool(true)
["result"]=> array(1)
{
[0]=> array(2)
{
["update_id"]=> int(44893465)
["message"]=> array(5)
{
["message_id"]=> int(16)
["from"]=> array(3)
{
["id"]=> int(29595794)
["first_name"]=> string(3) "Bob"
["username"]=> string(14) "Bobo"
}
["chat"]=> array(3)
{
["id"]=> int(29595794)
["first_name"]=> string(3) "Bob"
["username"]=> string(14) "Bobo"
}
["date"]=> int(1435354253)
["text"]=> string(7) "/q 3.33"
}
}
}
}
您使用了错误的数组索引<代码>$data[1][0][“用户名”]代码>不存在
$data["result"][0]["message"]["from"]["username"];
$data["result"][0]["message"]["chat"]["username"];
这将为您提供正确的用户名
$json = file_get_contents("url-here");
$data = json_decode($json, true);
//test
echo $data["result"][0]['message']['from']['username'];
输出
波波非常感谢。您对数组层次结构的表示对我帮助很大。在PHP中是否有这样的打印方法?我试过打印,但没有多大帮助。
var\u dump
是以这种方式显示数组的最佳方式。我不知道你为什么用var\u dump
得到这样的结果。尝试在
标记中显示。