0
{
   "AFL Round 16":{
      "4166082":{
         "EventID":4166082,
         "ParentEventID":3744759,
         "MainEvent":"North Melbourne v Hawthorn",   
         "OutcomeDateTime":"2014-07-06 02:00:00",    
         "Competitors":{
            "Competitors":[
               {
                  "Team":"Hawthorn To Win 40+",
                  "Win":"3.00"

               }
            ],
            "ActiveCompetitors":1,
            "TotalCompetitors":1,
            "HasWinOdds":true
         },
         "EventStatus":"Open"
      },
      "4167064":{
         "EventID":4167064,
         "ParentEventID":3744759,
         "MainEvent":"North Melbourne v Hawthorn", 
         "OutcomeDateTime":"2014-07-06 02:00:00",  
         "Competitors":{
            "Competitors":[
               {
                  "Team":"Hawthorn (-5.5)",
                  "Win":"1.86"

               },
               {
                  "Team":"North Melbourne (+5.5)",
                  "Win":"1.86"

               }
            ],
            "ActiveCompetitors":2,
            "TotalCompetitors":2,
            "HasWinOdds":true
         },
         "EventStatus":"Open"
      }

  }
}

I am parsing json objects using PHP and here is a sample of my json. Everything is working fine. I just want to check if object property/value exists if yes then throw errors for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.

This is few lines of my code.

$SortedByDate = array();//Sorted By Date Array i.e key=EventID and value=OutcomeDateTime


//Accessing Root Element0
foreach ($json_a as $root_element => $childnode) {
    //Accessing child elements
    foreach( $childnode as $cKey => $subChild) {
        $OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));

        //checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
        if($subChild['ParentEventID']=='0' and is_array($subChild['Competitors']['Competitors']) and count ($subChild['Competitors']['Competitors'])  == 2 and $OutcomeDateTime_UTC>=$NewDateTime and !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
            //Inserting values into array
            $SortedByDate[$cKey] = $subChild['OutcomeDateTime'];;
        }
    }
}

I tired to add if(isset($subChild['OutcomeDateTime']) || is_null($subChild['OutcomeDateTime'])) to check if property name is OutcomeDateTime and it is not null and change json proerty's value (OutcomeDateTime) to null but i get an error that "Invalid argument supplied for foreach()"

is there a better way to check property/values before parsing???

4
  • Any chance you can show how the value of $json_a is set? Commented Jul 3, 2014 at 0:22
  • $url= file_get_contents(""); $json_a=json_decode($url,true); Commented Jul 3, 2014 at 0:24
  • Just executed your code as it is and it runs fine. Not sure I understand the problem 100%, but it seems like maybe is_null($subChild['OutcomeDateTime'])) should be !is_null($subChild['OutcomeDateTime']))? Commented Jul 3, 2014 at 0:35
  • well i am not sure where to add this line is_null($subChild['OutcomeDateTime'])) . I am adding this after foreach( $childnode as $cKey => $subChild) {. Commented Jul 3, 2014 at 0:39

2 Answers 2

1

Try this and see if it does what you mean. If not, I don't understand. If it does solve your problem I'll explain why...

//Accessing Root Element0
foreach ($json_a as $root_element => &$childnode) {
    //Accessing child elements
    foreach( $childnode as $cKey => &$subChild) {
        $OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));

        //checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
        if($subChild['ParentEventID']=='0' && is_array($subChild['Competitors']['Competitors']) && count ($subChild['Competitors']['Competitors'])  == 2 && $OutcomeDateTime_UTC>=$NewDateTime && !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
            //Inserting values into array
            $SortedByDate[$cKey] = $subChild['OutcomeDateTime'];
        }
        if(isset($subChild['OutcomeDateTime']) && !is_null($subChild['OutcomeDateTime'])) {
            $subChild['OutcomeDateTime'] = null;
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

well its is the same and i tried this before when i am changing json "OutcomeDateTime":"2014-07-06 02:00:00" to "OutcomeDateTime":, then i am getting this error Invalid argument supplied for foreach(). i am adding else after your if like else { echo("OutcomeDateTime is empty"); exit(0); } so it should exist
I'm not sure what the problem is, but when executing both your code and mine I don't get the Invalid argument supplied for foreach() error at all. Maybe there's some more code that's changing $json_a before your loop or something, I don't know.
1

I just want to check if object property/value exists if yes then throw errors

Your wording doesn't make sense and little bit odd, maybe you were saying that you want to validate each key (if they exist) and if each value of those keys are not null

for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.

Here is a fiddle. Try to remove some elements inside the json string to check: Fiddle

$json_a = '{ "AFL Round 16":{ "4166082":{ "EventID":4166082, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn To Win 40+", "Win":"3.00" } ], "ActiveCompetitors":1, "TotalCompetitors":1, "HasWinOdds":true }, "EventStatus":"Open" }, "4167064":{ "EventID":4167064, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn (-5.5)", "Win":"1.86" }, { "Team":"North Melbourne (+5.5)", "Win":"1.86" } ], "ActiveCompetitors":2, "TotalCompetitors":2, "HasWinOdds":true }, "EventStatus":"Open" } }}';
$json_a = json_decode($json_a, true);
$json_a = reset($json_a); // ignore these parts since you already know how to get them

$errors = array();
$valid_keys = array('EventID', 'ParentEventID', 'OutcomeDateTime', 'MainEvent', 'Competitors', 'EventStatus');
foreach($json_a as $event_id => $values) {
    // check for keys
    $keys = array_keys($values);
    foreach($valid_keys as $key) {
        if(!in_array($key, $keys)) {
            // check keys, not valid if it goes here
            $errors[] = "<b>$key</b> is missing on your data <br/>";
        } else {
            // valid keys, check values
            if(empty($values[$key])) {
                // empty values
                $errors[] = "<b>$key</b> has an empty value <br/>";
            }
        }
    }

    // next checking, competitors
    foreach($values['Competitors']['Competitors'] as $competitors) {
        if(empty($competitors)) {
            // if competitors is empty
            $errors[] = "<b>Competitors</b> has an empty value <br/>";
        }
    }
}

if(!empty($errors)) {
    // not a good error triggering device, just change this to something else
    trigger_error('<pre>'.implode($errors).'</pre>', E_USER_ERROR);
}

Comments

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.