创建一个用于解析json数据的循环

时间:2018-02-08 02:57:19

标签: php json loops foreach

所以我想创建一个循环来解析我拥有的json数据。我可以在2个foreach循环中成功解析它,但是当尝试使用$ key =>组合在一个循环中时$ value $ key在调用时不返回任何内容。我怎样才能成功地将我在这里的2个foreach循环合并为一个?

$contents = file_get_contents($url);

$results = json_decode($contents, true);

$jsonList = $results['genres'];


foreach($jsonList as $key) {

$GenreID = $key['id'].'<br>';

echo $GenreID;
}


foreach($jsonList as $key => $value) {

$GenreName = $value['name'].'<br><br>';

echo $GenreName;
}

json数据如下:

{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

3 个答案:

答案 0 :(得分:2)

在提取$key

时,您仍然可以使用$value作为索引

但请注意,您不应该为您的变量指定换行符,而应该通过独立回显它们来将它们视为视图的一部分:

$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];

foreach($jsonList as $key => $value) {
  $GenreID = $key['id']; // Depending on structure, you may need $value['id'];
  $GenreName = $value['name'];
  echo $GenreID . '<br>';
  echo $GenreName . '<br><br>';
}

答案 1 :(得分:0)

Your single loop below here.

 foreach($jsonList as $key)
  {
 $GenreID = $key['id'].'<br>';
  echo $GenreID;
 $GenreName = $value['name'].'<br><br>'; 
echo $GenreName;
 }

$key is a assosative array.Therefore it had some index.So you can use this index in single loop.

答案 2 :(得分:0)

您似乎对数据结构感到困惑。看到j​​son,生成的“$ jsonlist”应该包含id和value作为键的数组。

您可以迭代它并提取相应的密钥。

Myabe是这样的:

foreach($jsonlist as $value) {
    echo "id: " . $value['id'] . "\n";
    echo "name: " . $value['name'] . "\n";
}

额外奖励,如果你想根据你的名字用你的json创建1级数组你可以尝试使用这样的anon函数进行数组减少:

$jsonlist = array_reduce($jsonlist, function($result, $item){ $result[$item['id']] = $item['name']; return $result; }, []);

用于转换静态结构数据的额外整洁。