Proper way to get attribute from json-Collection of common programming errors

 
              


There is an error in the code above: undefined offset on the line with the if. I guess it is because $getlikes[$key]['type'] is wrong. What would be the proper code to get all the objects with the type attribute being “like”?

Json can be downloaded from here

  1. This really depends on the content of your .json object. But most likely the undefined offset is being caused because not all $getlikes[$key] has an array key of ‘type’. Validate to make sure it exists before you compare. Try

    foreach ($get_json_values as $key=>$getlikes) { 
        if(!isset($getlikes['type'])) continue;
            if($getlikes['type']=='like') {
        ....
    

    EDIT:

    Based on your .json file you were just adding an additional key which was unneeded. Changed the code to reflect the correct call. Still not a bad idea to check if a value is set. Try a var_dump($getlikes) or on the file you are using to get a good look at what you are iterating over.

  2. Given the JSON string it’s clear what you’re doing wrong. $get_json_values is a list with no indexes, you’re doubling up on the key, hard to explain. Do this instead.

    foreach ($get_json_values as $getlikes) { 
        if($getlikes['type']=='like') {
    

    If you were to use $key, you’d use it like this

    foreach ($get_json_values as $key=>$getlikes) { 
        if($get_json_values[$key]['type']=='like') {
    

    but you wouldn’t do that anyway. Foreach extracts the elements one by one.

Originally posted 2013-11-10 00:11:47.