duanbei1709 2015-06-27 10:36
浏览 46
已采纳

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

I am obtaining a json object using the following:

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

This gives me something like this:

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" } } } }

I would then like to add certain values into variables. For example I would like to extract username, text, message_id, etc

But no matter what I try my variables are empty:

//let's test it
echo "Username: " . $data[1][0]["username"];

//another test
echo $data->username;

Neither of these are working and my research has not helped me find a solution. I am stumped on this one.

Any pointers in the right direction would really be appreciated.

  • 写回答

2条回答 默认 最新

  • doujumiao5024 2015-06-27 10:49
    关注
     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" 
                            } 
                    } 
            } 
        }
    

    You are using wrong array index. $data[1][0]["username"]; not exists.

    $data["result"][0]["message"]["from"]["username"]; 
    $data["result"][0]["message"]["chat"]["username"]; 
    

    This will give you the proper username

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?