Accessing JSON array after json_decode/multidimensional array

前端 未结 3 562
长情又很酷
长情又很酷 2020-11-30 15:18

I\'m pulling in a search from the Twitter api, fetching the data with file_get_contents and then passing to json_decode which give me this array structure.

{         


        
相关标签:
3条回答
  • 2020-11-30 15:48

    Assuming that you've chosen to decode the JSON as a multi-dimensional array, rather than as objects:

    foreach ($results as $tweet) {
        $user = $tweet["from-user"];
        $text = $tweet["text"];
    
        $entities = $tweet["enities"];
        $urls = $entities["urls"];
    
        foreach ($urls as $url) {
            echo $url["expanded_url"];
        }
    }
    

    et cetera

    0 讨论(0)
  • 2020-11-30 16:04

    Just do a print_r($jsonArr); and you will be able to work with your decoded json.

    0 讨论(0)
  • 2020-11-30 16:07
    Array
    (
        [results] => Array
            (
                [0] => stdClass Object
                    (
                        [entities] => Array
                            (
                                [0] => stdClass Object
                                    (
                                        [urls] => Array
                                            (
                                                [0] => stdClass Object
                                                    (
                                                        [expanded_url] => http://instagr.am/p/Vz4Nnbnjd6/
                                                        [url] => http://t.co/WZnUf68j
                                                    )
    
                                            )
    
                                    )
    
                            )
    
                        [from_user] => A-user-name
                        [from_user_id] => 457304735
                        [text] => Ich R U #BoysNoize #SuperRola
                    )
    
            )
    
    )
    

    Accessing url:

    $json_array['results'][0]->entities[0]->urls[0]->url;
    

    Helpful code:

    <?php
    
    $json ='{ "results" : [ { "entities" : 
    [ { "urls" : [ { "expanded_url" : "http://instagr.am/p/Vz4Nnbnjd6/",
                        "url" : "http://t.co/WZnUf68j"
                      } ] } ],
            "from_user" : "A-user-name",
            "from_user_id" : 457304735,
            "text" : "Ich R U #BoysNoize #SuperRola"
          } ] }';
    $json_array = (array)(json_decode($json));
    echo '<pre>';
     //print_r($json_array);
    
     echo $json_array['results'][0]->entities[0]->urls[0]->url;
    

    ?>

    0 讨论(0)
提交回复
热议问题