【问题标题】:How to refer to data in an array (php/json)如何引用数组中的数据(php/json)
【发布时间】:2015-09-14 06:26:34
【问题描述】:

我正在使用以下方法获取 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(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" } ["聊天"]=> 数组(3) { ["id"]=> int(29595794) ["first_name"]=> 字符串(3) "鲍勃" ["用户名"]=> 字符串(14) "鲍勃" } ["日期"]=> int(1435354253) ["text"]=> string(7) "/q 3.33" } } } }

然后我想将某些值添加到变量中。例如我想提取用户名、文本、message_id 等

但无论我尝试什么,我的变量都是空的:

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

//another test
echo $data->username;

这些都不起作用,我的研究也没有帮助我找到解决方案。我被这个难住了。

任何指向正确方向的指针都将不胜感激。

【问题讨论】:

    标签: php arrays json


    【解决方案1】:
     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"]; 
    

    这将为您提供正确的用户名

    【讨论】:

    • 非常感谢。您对数组层次结构的表示对我帮助很大。 PHP中是否有打印类似内容的方法?我试过 print_r 但它没有那么有用。
    • var_dump 是以这种方式显示数组的最佳方式。我不知道你为什么用var_dump 得到这样的结果。尝试显示在<pre></pre> 标签中。 stackoverflow.com/questions/5393085/…
    【解决方案2】:
    $json = file_get_contents("url-here");
    $data = json_decode($json, true);
    //test
    
    echo $data["result"][0]['message']['from']['username'];
    

    输出 波波

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-12
      • 2021-05-17
      • 2011-04-11
      • 1970-01-01
      • 2023-02-04
      • 2023-01-08
      • 1970-01-01
      • 2017-10-20
      相关资源
      最近更新 更多