0

I'm using json_decode on this json data here:

issues": [

 {
    "id": "51526",
    "key": "123",
    "fields": {
        "zone": [
            {
                "name": "football",
                "active": true
            },
            {
                "name": "baseball",
                "active": true
            }
        ],
        "icon": {
            "id": "1"
        }
    }
},
{
    "id": "51228",
    "key": "3108",
    "fields": {
        "zone": null,
        "icon": {
            "id": "10"
            }
        }
    }
 ]

}

I can properly extract the name data which will be ["football", "baseball"]. However, I also want to capture the null value from the 2nd data set so my data really looks like

 ["football", "baseball", null].

Basically, I want to look at "zone" and get the value of "name", if "zone" is null then the value is null in order to get this data structure ["football", "baseball", null].

I've tried everything I could think of, but I'm not great at php. Is this possible to do?

Php code:

$decoded_array = json_decode($result)->{'issues'};           
            foreach($decoded_array as $issues){                        
            foreach($issues->{'fields'}->{'zone'} as $zn){  
            $nm[] = $zn->{'name'};           
  }
}
1
  • Please post some code you use for your task Commented Apr 4, 2014 at 18:33

2 Answers 2

1

You can do something like this:

$data = json_decode($json);
$issues = $data->issues;

$names = array();
foreach($issues as $issue){
  $zones = $issue->fields->zone;
  foreach($zones as $zone){
    if($zone != null){
        $name = $zone->name;
        array_push($names,$name);   
    }else{
        array_push($names,null);
    }
  }      
}
Sign up to request clarification or add additional context in comments.

Comments

0

When you iterate the json object, check if "zone" is null. If it is, you can add null in your result array.

Pseudo code:

Iterate jsonObject 
  if (jsonObject["fields"]["zone"] == null)
  then push_in_array(result,null)

2 Comments

When you add null in your result array, is it simply appending null to the result. Or will it be placed within its original position as seen within the json?
you can have something like this: [ "51526"=>"football", "51526"=>"baseball", "51228"=>null ] Essentially, you can bind each value with a unique value. It can be any unique value for each dataset. Or you can simply bind with array indexes starting from 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.