duanbei1709
2015-06-27 10:36
浏览 44

如何引用数组中的数据(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

    已采纳该答案
    打赏 评论
  • dongwei4096 2015-06-27 10:55
    $json = file_get_contents("url-here");
    $data = json_decode($json, true);
    //test
    
    echo $data["result"][0]['message']['from']['username'];
    

    output Bobo

    打赏 评论

相关推荐 更多相似问题