Viewed   136 times

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.

{"results":[
     {
     "from_user":"A-user-name",
     "from_user_id":457304735,
     "text":"Ich R U #BoysNoize #SuperRola",

          "entities":{

                 "urls":[{
                        "url":"http://t.co/WZnUf68j",
                        "expanded_url":"http://instagr.am/p/Vz4Nnbnjd6/",
                        }]

     }]
]

This repeats for every tweet pulled, Now I can access the user name and text using a foreach loop and assigning every instance of results to a variable, then pulling data from the variable.

foreach($jsonArr['results'] as $item){    

// Takes the Array jsonArr and for every results heading creates an $item

    $user = mysql_real_escape_string($item['from_user']);
    $text = mysql_real_escape_string($item['text']);

This saves the correct variables OK, But I can't seem to get the the data within the entities array within the results. If I print out the Entities var like the username or text I get

ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

So It holds the arrays for each results returned but how on earth do I access it, I've been messing around with a few other methods I know for accessing array data but they all seem to fall flat. Any help with how to get at these values, or integrate them with the foreach would be greatly appreciated

 Answers

3

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

Thursday, August 4, 2022
1

decode your json as array and iterate it as any array as flowing:

$json_decoded= json_decode($json,true);

$tab="t";

foreach ($json_decoded as $key => $val) {
    echo "Article ".$val["key"]."n" ;
    echo $tab."Authors :n";
    foreach ($val["data"]["authors"] as $key => $author){
        echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."n";
    } 

    echo $tab."Article Title: ".$val["data"]["articleTitle"] ."n";
    echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."n";
    echo $tab."Key: ".$val["key"]."n";
}

run on codepad

and you can use the same method for xml as flowing:

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same

for xml you can use the SimpleXml's functions or DOMDocument class


Tip

to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging

Sunday, October 30, 2022
 
2

Try echo count($task_array['task']);

In general, if you wonder what the structure of the value of a variable $var is, do a

<pre><?php var_export($var, true); ?></pre>

Advantage of this function over alternatives such as serialize and print_r is, that it prints PHP code (and is thus readable by anyone who understands PHP (which is likely if you program in PHP)). Disadvantage of var_export is, that it cannot handle circular structures (e.g. if $a->b == $a), but neither can JSON.

Sunday, September 11, 2022
5

To get all from phoneNumbers:

DECLARE @json nvarchar(max)=
    '{
      "firstName": "John",
      "lastName" : "doe",
      "age"      : 26,
      "address"  : {
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
      },
      "phoneNumbers": [
        {
          "type"  : "iPhone",
          "number": "0123-4567-8888"
        },
        {
          "type"  : "home",
          "number": "0123-4567-8910"
        }
      ]
    }'

    SELECT [Type], [Number]
    FROM OPENJSON( @json, '$.phoneNumbers' ) 
    WITH ([Type] NVARCHAR(25) '$.type', [Number] NVARCHAR(25) '$.number');
Thursday, November 17, 2022
4

As the error says, interface variables do not support indexing. You will need to use a type assertion to convert to the underlying type.

When decoding into an interface{} variable, the JSON module represents arrays as []interface{} slices and dictionaries as map[string]interface{} maps.

Without error checking, you could dig down into this JSON with something like:

objects := result["objects"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["ITEM_ID"])

These type assertions will panic if the types do not match. You can use the two-return form, you can check for this error. For example:

objects, ok := result["objects"].([]interface{})
if !ok {
    // Handle error here
}

If the JSON follows a known format though, a better solution would be to decode into a structure. Given the data in your example, the following might do:

type Result struct {
    Query   string `json:"query"`
    Count   int    `json:"count"`
    Objects []struct {
        ItemId      string `json:"ITEM_ID"`
        ProdClassId string `json:"PROD_CLASS_ID"`
        Available   int    `json:"AVAILABLE"`
    } `json:"objects"`
}

If you decode into this type, you can access the item ID as result.Objects[0].ItemId.

Saturday, November 5, 2022
 
davidm
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :