PHP显示所选数组索引的值

时间:2018-06-18 06:51:55

标签: php arrays json

我在项目中使用此JSON:http://mysafeinfo.com/api/data?list=us_bestitjobcities2015&format=json

作为一个数组,它看起来像这样:

array(28) {
  [0]=>
  array(7) {
    ["yr"]=>
    string(4) "2015"
    ["nm"]=>
    string(7) "Seattle"
    ["cd"]=>
    string(2) "WA"
    ["cst"]=>
    float(107)
    ["sal1"]=>
    int(107540)
    ["sal2"]=>
    int(79945)
    ["sal3"]=>
    int(72639)
  }
  [1]=>
  array(7) {
    ["yr"]=>
    string(4) "2015"
    ["nm"]=>
    string(8) "San Jose"
    ["cd"]=>
    string(2) "CA"
    ["cst"]=>
    float(122)
    ["sal1"]=>
    int(107121)
    ["sal2"]=>
    int(73367)
    ["sal3"]=>
    int(84530)
  }
  [2]=>
  array(7) {
    ["yr"]=>
    string(4) "2015"
    ["nm"]=>
    string(7) "Raleigh"
    ["cd"]=>
    string(2) "NC"
    ["cst"]=>
    float(95.2)
    ["sal1"]=>
    int(102950)
    ["sal2"]=>
    int(87131)
    ["sal3"]=>
    int(71758)
  }
}

我创建的是一个带有下拉菜单的页面,该菜单中填充了网络上的JSON文档中某些字段的数据。我想要做的是,当你从下拉菜单中选择一个值时,页面将显示一个“关联”值(如果我理解这一点,则在同一索引中的值)。

下拉菜单中填充了“nm”字段中的数据。

因此,例如,如果您从下拉菜单中选择“西雅图”,我希望页面显示(通过回声或类似的东西)与该字段关联的“sal1”值。与“Seattle”相关联的“sal1”字段具有值“107540”。我不想显示其他“sal1”值(例如与圣何塞相关的值,值为“107121”。

我的代码如下所示:

<?php
$url = 'http://mysafeinfo.com/api/data?list=us_bestitjobcities2015&format=json';

$jsonData = file_get_contents($url);
$jsonArray = json_decode($jsonData, true);

//var_dump($jsonArray);
//echo gettype($jsonArray);

echo 
'<form action="index.php" method="get" name=phpform">
<select name="state">';
foreach($jsonArray as $data){
  echo '<option value="' . $data . '">' . $data['nm'] . '</option>';
  }

echo
'</select> 
<input type="submit" value="Velg" name="submitphp"></input>
</form>';
?>

<!doctype html> 
<html>
<head>
    <title>Vareliste</title>
</head>
<body>
    <?php   
    if(isset($_POST['submitphp'])) {
        foreach($jsonArray as $nr => $nr_value) {
            if($nr_value==$_GET['state']) echo $nr['sal1'];
        }
    }
    else echo "NA";
    ?>
</body>
</html>

有什么办法可以做我想做的事吗?

0 个答案:

没有答案