2014-10-30 126 views
-2

我有这个数组结构我想要得到具有14个值的小时后发现我需要获得该数组的索引,我需要过滤其他元素请帮忙。从JSON文件中获取PHP数组的索引值

$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');  
} 
+1

请向我们展示您的字符串内容。 – vaso123 2014-10-30 18:58:48

+0

@lolka_bolka只要浏览[url](http://api.wunderground.com/api/aa433737d95d5869/hourly/q/US/Los%20Angeles%20International.json) – AlexP 2014-10-30 19:01:38

+1

所以你只需要这个数组,有什么价值14还是那个指数? – vaso123 2014-10-30 19:03:44

回答

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); 
    } 
} 
0

我不知道我理解的问题,但如果你想挑选出FCTTIME项目,其中hour等于14,你可以做这样的:

$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 
    } 
} 
1

可以使用的foreach这样让每个键=>值对,做任何你想要的:

<?php 
foreach ($json as $key => $value) { 
    if ($key === "hour") { 
     if ($value === "14") { 
      // do whatever 
     } 
    }  
} 
?> 

从你展示的api看来,你不得不深入探索数组,但这就是你如何实现你想要的。