我有一个复杂的json数组,我想定位一个特定的行/字符串,如果存在,那么在网页上添加一个小表...
这是数组
{
"coastalWarnings":[{
"loc":"ABEL",
"warn":"GALE"
},{
"loc":"CASTLEPOINT",
"warn":"STORM"
},{
"loc":"CHALMERS",
"warn":"GALE"
},{
"loc":"CHATHAM ISLANDS",
"warn":"GALE"
},{
"loc":"CONWAY",
"warn":"STORM"
},{
"loc":"COOK",
"warn":"STORM"
},{
"loc":"FOVEAUX",
"warn":"GALE"
},{
"loc":"GREY",
"warn":"GALE"
},{
"loc":"MILFORD",
"warn":"STORM"
},{
"loc":"PORTLAND",
"warn":"GALE"
},{
"loc":"PUYSEGUR",
"warn":"STORM"
},{
"loc":"RAGLAN",
"warn":"GALE"
},{
"loc":"RANGITATA",
"warn":"GALE"
},{
"loc":"STEPHENS",
"warn":"GALE"
}
],
"isAdvisory":true,
"isOutlook":true,
"isVhf":true,
"isWatch":true,
"liftedWarnings":[
],
"oceanicWarnings":[{
"loc":"FORTIES",
"warn":"GALE"
},{
"loc":"PACIFIC",
"warn":"GALE"
},{
"iceAccretion":true,
"loc":"SOUTHERN",
"warn":"GALE"
},{
"loc":"SUBTROPIC",
"warn":"GALE"
}
],
"roadSnowWarnings":[
],
"severeWarnings":[{
"loc":"BULLER",
"warn":["ISSUE"
]
},{
"loc":"CANTERBURY",
"warn":["ISSUE"
]
},{
"loc":"FIORDLAND",
"warn":["ISSUE"
]
},{
"loc":"HAWKES BAY",
"warn":["ISSUE"
]
},{
"loc":"MANAWATU",
"warn":["ISSUE"
]
},{
"loc":"MARLBOROUGH",
"warn":["ISSUE"
]
},{
"loc":"NELSON",
"warn":["ISSUE"
]
},{
"loc":"OTAGO",
"warn":["ISSUE"
]
},{
"loc":"SOUTHLAND",
"warn":["ISSUE"
]
},{
"loc":"TAIHAPE",
"warn":["ISSUE"
]
},{
"loc":"TARANAKI",
"warn":["ISSUE"
]
},{
"loc":"TAUMARUNUI",
"warn":["ISSUE"
]
},{
"loc":"TAUPO",
"warn":["ISSUE"
]
},{
"loc":"WAIRARAPA",
"warn":["ISSUE"
]
},{
"loc":"WAITOMO",
"warn":["ISSUE"
]
},{
"loc":"WANGANUI",
"warn":["ISSUE"
]
},{
"loc":"WELLINGTON",
"warn":["ISSUE"
]
},{
"loc":"WESTLAND",
"warn":["ISSUE"
]
}
],
"thunderstormWarnings":[
]
}
正如您所看到的,阵列被分解为部分 -
"coastalWarnings"
"liftedWarnings"
"oceanicWarnings"
"roadSnowWarnings"
"severeWarnings"
"thunderstormWarnings"
我希望定位“严重警告”,特别是“loc”:“CANTERBURY”,显示为 -
},{
"loc":"CANTERBURY",
"warn":["ISSUE"
]
},{
因此,当存在于数组中时,它将触发一个表,例如
<table align="center" width="100%" bgcolor="red">
<tr><td><strong>Severe Weather Warning in effect for CANTERBURY</strong></td></tr>
</table>
最大的问题是阵列一直在变化所以我需要通过搜索特定的单词或措辞来定位,除非它可以被可靠地分解成部分。
这可以简单吗?
<?
$table = <table align="center" width="100%" bgcolor="red"><tr><td><strong>Severe Weather Warning in effect for CANTERBURY</strong></td></tr></table>;
$file = file_get_contents("filename.ext");
if(!strpos($file, ""loc":"CANTERBURY"")) {
echo $table;
}
?
不确定如何解决这个问题,我的PHP技能相当有限,所以如果你非常友好地向我展示一个脚本或一步一步如何实现这一点,我会非常感激。
提前致谢。
答案 0 :(得分:1)
正如Alex建议的那样,使用json_decode
$s = getData(); // returning the string from the question
$data = json_decode($s, true);
foreach( $data['severeWarnings'] as $cw ) {
if ( 'CANTERBURY'===$cw['loc'] ) {
foreach( $cw['warn'] as $msg ) {
echo "-- ", $msg, " --\n";
}
}
}
打印-- ISSUE --