从json对象获取特定键

时间:2018-01-27 13:51:28

标签: php arrays json

您好我试图解析一些JSON对象的密钥,代码现在正常工作,但我不想解析所有密钥,就像前6个一样。

这是JSON

{
"results":[
  {
     "name":"Luke Skywalker",
     "height":"172",
     "mass":"77",
     "hair_color":"blond",
     "skin_color":"fair",
     "eye_color":"blue",
     "birth_year":"19BBY",
     "gender":"male"
  },
  {
     "name":"C-3PO",
     "height":"167",
     "mass":"75",
     "hair_color":"n/a",
     "skin_color":"gold",
     "eye_color":"yellow",
     "birth_year":"112BBY",
     "gender":"n/a"
  },
  {
     "name":"R2-D2",
     "height":"96",
     "mass":"32",
     "hair_color":"n/a",
     "skin_color":"white, blue",
     "eye_color":"red",
     "birth_year":"33BBY",
     "gender":"n/a"
  },
  {
     "name":"Darth Vader",
     "height":"202",
     "mass":"136",
     "hair_color":"none",
     "skin_color":"white",
     "eye_color":"yellow",
     "birth_year":"41.9BBY",
     "gender":"male"
  },
  {
     "name":"Leia Organa",
     "height":"150",
     "mass":"49",
     "hair_color":"brown",
     "skin_color":"light",
     "eye_color":"brown",
     "birth_year":"19BBY",
     "gender":"female"
  },
  {
     "name":"Owen Lars",
     "height":"178",
     "mass":"120",
     "hair_color":"brown, grey",
     "skin_color":"light",
     "eye_color":"blue",
     "birth_year":"52BBY",
     "gender":"male"
  },
  {
     "name":"Beru Whitesun lars",
     "height":"165",
     "mass":"75",
     "hair_color":"brown",
     "skin_color":"light",
     "eye_color":"blue",
     "birth_year":"47BBY",
     "gender":"female"
  },
  {
     "name":"R5-D4",
     "height":"97",
     "mass":"32",
     "hair_color":"n/a",
     "skin_color":"white, red",
     "eye_color":"red",
     "birth_year":"unknown",
     "gender":"n/a"
  },
  {
     "name":"Biggs Darklighter",
     "height":"183",
     "mass":"84",
     "hair_color":"black",
     "skin_color":"light",
     "eye_color":"brown",
     "birth_year":"24BBY",
     "gender":"male"
  },
  {
     "name":"Obi-Wan Kenobi",
     "height":"182",
     "mass":"77",
     "hair_color":"auburn, white",
     "skin_color":"fair",
     "eye_color":"blue-gray",
     "birth_year":"57BBY",
     "gender":"male"
     }
    ]
    }

这是我的代码(当您点击列表中的某个人时,您会获得详细信息):

<hr>
<h3>Details</h3>
<?php 
$id=$_POST['id'];
$url="https://swapi.co/api/people/".$id."/";
$json = file_get_contents($url);
$array = json_decode($json, true);
foreach($array as $a => $b){
    ?>
        <span><?php echo ucfirst($a);?> : <?php echo $b; ?></span>
        <br>
    <?php
}
?>

我试图用以下代码改变foreach:

foreach($array['results'] as $a => $b) {
    $name=$b['name'];
    $height=$b['height];

但得到一个:

  

警告:为

中的foreach()提供的参数无效

0 个答案:

没有答案