PHP Json对象属性/值错误处理

时间:2014-07-03 00:16:12

标签: php json

{
   "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"
      }

  }
}

我使用PHP解析json对象,这是我的json示例。一切都很好。我只想检查对象属性/值是否存在,如果是,则抛出错误,例如我想检查EventID,ParentEventID,OutcomeDateTime,Team(在Competitors数组中)是有效的属性名称,它们不是null。

这是我的代码中的几行。

$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'];;
        }
    }
}

我厌倦了添加if(isset($subChild['OutcomeDateTime']) || is_null($subChild['OutcomeDateTime']))以检查属性名称是否为OutcomeDateTime并且它不为null并将json proerty的值(OutcomeDateTime)更改为null但我收到"Invalid argument supplied for foreach()" <的错误/ p>

在解析???

之前有更好的方法来检查属性/值

2 个答案:

答案 0 :(得分:1)

  

我只想检查对象属性/值是否存在,如果是,则抛出错误

你的措辞没有意义,有点奇怪,也许你说要验证每个密钥(如果存在)以及这些密钥的每个值是否为空

  

例如我想检查EventID,ParentEventID,OutcomeDateTime,Team(在Competitors数组中)是有效的属性名称,它们不是null。

这是一个小提琴。尝试删除json字符串中的一些元素以检查: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);
}

答案 1 :(得分:1)

试试这个,看看它是否符合您的意思。如果没有,我不明白。如果它确实解决了你的问题,我会解释原因......

//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;
        }
    }
}