如何引用数组中的数据(php/json)


How to refer to data in an array (php/json)

我正在使用以下方法获取json对象:

$json = file_get_contents("url-here");
$data = json_decode($json, true);
//test
var_dump($data);

这给了我这样的东西:

array(2){["ok"]=>bool(true)["result"]=>array(1){[0]=>array{["update_id"]=>int(44893465)["message"]=>数组(5){["message_id"]=>int(16)["from"]=>array(3){["id"]=>int(29595794)["first_name"]=>string(3)"Bob"["username"]=>字符串(14)"Bobo"}["chat"]=>数组(3){["id"]=>int(29595794)["first_name"]=>string(3)"Bob"["username"]=>string(14)"Bobo"}["date"]=>int(1435354253)["text"]=>字符串(7)"/q 3.33"}}}}

然后,我想将某些值添加到变量中。例如,我想提取用户名、文本、message_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]["username"];不存在。

$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'];

输出波波