2014-05-12 04:43
浏览 51


I have to parse this json data using PHP and store the values into PHP variables.

"sender": "",  
"receiver": "",  
"msg_id": "",   
"subject": "Group Discussion",   
"references": ["","",""]

I am using this PHP code, its not working; pls check it.

For the fields 'sender', 'receiver', 'msg_id'and 'subject, I am using PHP variables '$msg_id', '$sender', '$receiver' and '$subject'.
I am trying to store the data of 'references' in the array 'ref_id'.

Also, the file 'dataset_f.json' has content in the following way:

{ "sender":"","receiver":"","msg_id":"","subject": "Project Discussion","references":["","",""]}

{ "sender":"","receiver":"","msg_id":"","subject": "Project Discussion","references":["","",""]}

Thats why the php code is reading the file line by line

$h1 = fopen("dataset_f.json", "r");
$line = fgets($h1);
$test_case = json_decode($line);

$ref_id = array();
$msg_id = $test_case->{'msg_id'};
$sender = $test_case->{'sender'};
$receiver = $test_case->{'receiver'};
$subject = $test_case->{'subject'};
foreach($test_case as $val)
    foreach($val -> references as $refer)
        array_push($ref_id, $refer->ref);

// printing the values
 { echo $ref_id[$x]." "; }
echo $msg_id." ".$sender." ".$receiver." ".$subject." <br> ";

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsagzmosl32217092 2014-05-12 05:14

    Store the whole file as a string, decode it and store the values in you variables. Show the json your using. your using the -> incorrect, thats for objects not arrays, json_decode() returns an associative array if the next param is true. ref_id will hold a string thats comma separated.


        "subject":"Group Discussion",

    php code

    $json = file_get_contents("dataset_f.json");
    $data = json_decode($json, true);
    // here depends on the json
    $ref_id = ( ( is_array( $data["references"] ) ? implode(", ", $data["references"]) : $data["references"] ) ); // array to string
    $msg_id = $data["msg_id"];
    $sender = $data["sender"];
    $receiver = $data["receiver"];
    $subject = $data["subject"];
    打赏 评论

相关推荐 更多相似问题