我有这个数组结构,在发现我需要获得该数组的索引后,我想获得值为14的小时,我需要过滤其他元素,请帮助。
$string = file_get_contents("http://api.wunderground.com/api/aa433737d95d5869/hourly/q/US/Los%20Angeles%20International.json");
$json = json_decode($string, true);
foreach ($json as $value) {
echo "<pre>";
print_r($value);
echo "</pre>";
print_r(search($value, 'hour', '14'));
echo find_parent($value, '14');
}
开始:
$json = json_decode($string, true);
foreach ($json['hourly_forecast'] as $key => $val) {
if ($val['FCTTIME']['hour'] == 14) {
die('The key is where hour is 14 is: ' . $key);
}
}
您可以像这样使用foreach来获取每个key=>值对,并执行任何您想要的操作:
<?php
foreach ($json as $key => $value) {
if ($key === "hour") {
if ($value === "14") {
// do whatever
}
}
}
?>
从您展示的api来看,您似乎需要对数组进行更深入的挖掘,但这就是您实现所需内容的方式。
我不确定我是否理解这个问题,但如果你想挑选hour
等于14的FCTTIME
项目,你可以这样做:
$json = file_get_contents("http://api.wunderground.com/api/aa433737d95d5869/hourly/q/US/Los%20Angeles%20International.json");
// decode the json string
$object = json_decode($json);
// loop through each `hourly_forecast` item and check if `FCTTIME->hour` is equal to 14
foreach ($object->hourly_forecast as $index => $forecast) {
if($forecast->FCTTIME->hour == 14) {
// the $index contains the items position in the `hourly_forecast` array
}
}