如何用PHP遍历JSON文件并访问其中的第二个元素?
我手头有一个包含地理坐标和一些特征的JSON文件,像这样:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"mapImage": "start",
"city": "XXX",
"hdColor": "#8c0303",
"iconWind": "mbike",
"place": "xxx",
"progressive": "xxx",
"step": "1",
"icon": "start_icon",
"mapPoint": "start",
"routeColor": "#ff0000"
},
"geometry": {
"type": "Point",
"coordinates": [10.64396439843723, 44.69265308192274]
}
},
{
"type": "Feature",
"properties": {
"mapImage": "start",
"city": "YYY",
"hdColor": "#8c0303",
"iconWind": "mbike",
"place": "xxx",
"progressive": "xxx",
"step": "2",
"icon": "start_icon",
"mapPoint": "start",
"routeColor": "#ff0000"
},
"geometry": {
"type": "Point",
"coordinates": [10.64396439843723, 44.69265308192274]
}
}
]
}
显然,这只是第一个元素,但文件里有很多类似的特征项。
我需要遍历这些文件,使用如下代码:
$file = file_get_contents('file.json');
$path = json_decode($file);
if (JSON_ERROR_NONE !== json_last_error()) {
printf("%s", json_last_error_msg());
exit;
}
}
foreach ($path->features as $routes) {
$start = $routes->properties->city);
finish = ??? //point to the city element in the next 'feature'
}
同样地,很明显,我只摘录了理解问题所需的部分。
在PHP代码中,我需要指向第二个“特征项”的CITY元素,在本例中是YYY。我需要在不修改 foreach 循环迭代的前提下完成,因为下一步,我还需要再次指向当前“特征项”的CITY元素(此时它已经变成第2 个,即YYY)以及它的下一个元素。
实际操作中,我应该在整个文件的“特征项”持续期间,总是取得当前CITY元素和下一个CITY元素:
为便于理解:
我需要的是第一和第二个、第二和第三个、第三和第四个、第四和第五个、第五和第六个……以此类推。
我在PHP里找不到可用的语法。
我也尝试用 while 迭代。在简单数组里运作良好,但应用到这里我却搞不定。
解决方案
你需要在循环中增加一个键,这样就能用它来引用下一个元素。不过,在循环结束时会遇到一个问题,但这也可以很容易地处理。
foreach ($path->features as $key => $routes) {
$start = $routes->properties->city;
if(array_key_exists($key+1, $path->features))
$finish = $path->features[$key + 1]->properties->city;
else $finish = '';
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。