使用 PHP/Laravel 解析 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42720106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JSON file using PHP/Laravel
提问by Zach Tackett
I have a JSON that I need to parse.
我有一个需要解析的 JSON。
{
"Room 251": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 318": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 319 (Friends Room)": {
"calID": "[email protected]",
"availMsg": "Available For Study"
},
"Room 323": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 513 (Voinovich Room)": {
"calID": "[email protected]",
"availMsg": "Available For Study"
}
}
I need to obtain the room name, the calID, and the available message. What would be the best way to go about doing this in PHP/Laravel?
我需要获取房间名称、calID 和可用消息。在 PHP/Laravel 中执行此操作的最佳方法是什么?
回答by Lucas Martins
You can use json_decode
to parse a json data.
您可以使用json_decode
来解析 json 数据。
mixed json_decode ( string $json [, bool $assoc ] )
混合 json_decode ( 字符串 $json [, bool $assoc ] )
For example:
例如:
$rooms = json_decode($yourJsonHere, true);
var_dump($rooms);
foreach($rooms as $name => $data) {
var_dump($name, $data['calID'], $data['availMsg']); // $name is the Name of Room
}
回答by Vincent G
You can do something like that :
你可以这样做:
<?php
$json = '
{
"Room 251": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 318": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 319 (Friends Room)": {
"calID": "[email protected]",
"availMsg": "Available For Study"
},
"Room 323": {
"calID": "[email protected]",
"availMsg": "Open Computer Lab"
},
"Room 513 (Voinovich Room)": {
"calID": "[email protected]",
"availMsg": "Available For Study"
}
}';
foreach(json_decode($json) as $room_name => $room){
echo $room_name.'<br/>'; // output the room name, for instead "Room 251"
echo $room->calID.'<br/>'; // output the room calID
echo $room->availMsg.'<br/>'; // output the room availMsg
}
?>