我有这个数组结构我希望得到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');
}
答案 0 :(得分:1)
你走了:
$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);
}
}
答案 1 :(得分:1)
您可以像这样使用foreach来获取每个键=&gt;价值对,做任何你想做的事情:
<?php
foreach ($json as $key => $value) {
if ($key === "hour") {
if ($value === "14") {
// do whatever
}
}
}
?>
从你展示的api来看,你似乎不得不深入挖掘阵列,但这就是你如何达到你想要的目标。
答案 2 :(得分:0)
我不确定我是否理解这个问题,但是如果你想挑选FCTTIME
等于hour
的项目,你可以这样做:
$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
}
}