在PHP中解码JSON的特定元素

问题描述:

我正在尝试解码JSON在PHP中解码JSON的特定元素

我正在通过STOMP读取JSON。有不同的JSON数据集,所以我需要确定哪个JSON数据集已经通过。我通过阅读它的标题来做到这一点。

不过有我有麻烦读

foreach (json_decode($msg->body,true) as $event) { 
    if(isset($event['schemaLocation'])) { 
    $schedule_id=($event['schedule']['schedule_start_date']); 
    $signalling_id=($event['schedule']['schedule_segment']['signalling_id']); 

    echo $schedule_id; 
    } 

在上面的例子中isset功能工作正常,也$ schedule_id然而$ signalling_id给出了一个错误得到正确的答案

一个特定的数据集未定义的索引:

这是JSON部分的转储(其相当长............)。带有signalling_id的JSON片断是在第e JSON。任何帮助获得变量signalling_id非常赞赏。

array(7) { 
    ["schemaLocation"]=> 
    string(72) "http://xml.networkrail.co.uk/ns/2008/Train itm_vstp_cif_messaging_v1.xsd" 
    ["classification"]=> 
    string(8) "industry" 
    ["timestamp"]=> 
    string(13) "1410374918000" 
    ["owner"]=> 
    string(12) "Network Rail" 
    ["originMsgId"]=> 
    string(47) "2014-09-10T18:48:38-00:00vstp.networkrail.co.uk" 
    ["Sender"]=> 
    array(3) { 
     ["organisation"]=> 
     string(12) "Network Rail" 
     ["application"]=> 
     string(4) "TOPS" 
     ["component"]=> 
     string(4) "VSTP" 
    } 
    ["schedule"]=> 
    array(11) { 
     ["schedule_id"]=> 
     string(0) "" 
     ["transaction_type"]=> 
     string(6) "Create" 
     ["schedule_start_date"]=> 
     string(10) "2014-09-10" 
     ["schedule_end_date"]=> 
     string(10) "2014-09-10" 
     ["schedule_days_runs"]=> 
     string(7) "0010000" 
     ["applicable_timetable"]=> 
     string(1) "N" 
     ["CIF_bank_holiday_running"]=> 
     string(1) " " 
     ["CIF_train_uid"]=> 
     string(6) "W64017" 
     ["train_status"]=> 
     string(1) "1" 
     ["CIF_stp_indicator"]=> 
     string(1) "O" 
     ["schedule_segment"]=> 
     array(1) { 
     [0]=> 
     array(20) { 
      ["signalling_id"]=> 
      string(4) "5Y75" 
      ["uic_code"]=> 
      string(0) "" 
      ["atoc_code"]=> 
      string(0) "" 
      ["CIF_train_category"]=> 
      string(2) "EE" 
      ["CIF_headcode"]=> 
      string(0) "" 
      ["CIF_course_indicator"]= 
      ............................................ 

schedule_segment本身是一个数组,所以不是

['schedule']['schedule_segment']['signalling_id']); 

,可能应该是

['schedule']['schedule_segment'][0]['signalling_id']); 
+0

非常感谢,作品 – user2635961 2014-09-10 19:46:04

正如你可以在var转储看,signalling_id是另一个数组中。用途:

$signalling_id=($event ['schedule']['schedule_segment'][0]['signalling_id']); 

如果用0键是一个元件阵列始终不是恒定的,你可能需要一些逻辑来弄清楚它是什么,在每个迭代。

+0

只是现在测试,谢谢。等待JSON通过STOMP – user2635961 2014-09-10 19:18:59

+0

非常感谢 – user2635961 2014-09-10 19:46:37