在PHP中,如何在get_内容中循环URL查询字符串的值并回显相应的数据?
我试图从一个API解析一些数据,该API的结果是json格式的。 我能够成功地为一个参数执行此操作,如下面的代码所示,该代码输出了我所期望的一些数据在PHP中,如何在get_内容中循环URL查询字符串的值并回显相应的数据?,php,arrays,json,Php,Arrays,Json,我试图从一个API解析一些数据,该API的结果是json格式的。 我能够成功地为一个参数执行此操作,如下面的代码所示,该代码输出了我所期望的一些数据 $json=get_content('site.tld/api.php?country=0'); $decode=json_decode($json); 回声“俄罗斯:”.$decode->kt 我想用数组(0,1,2,5,10,20等)更改get_内容中country QueryString的值,该数组应相应地更改echo输出中的值。基本上是另一
$json=get_content('site.tld/api.php?country=0');
$decode=json_decode($json);
回声“俄罗斯:”.$decode->kt代码>
我想用数组(0,1,2,5,10,20等)更改get_内容中country QueryString的值,该数组应相应地更改echo输出中的值。基本上是另一组数组。
示例:0应对应于俄罗斯(这是默认情况)。1个去美国,2个去巴西,5个去哈萨克斯坦,依此类推
我只能考虑对每个国家的价值重复上述代码,如下所示:
$json=get_content('site.tld/api.php?country=0');
$decode=json_decode($json);
回声“俄罗斯:”.$decode->kt代码>
$json=get_content('site.tld/api.php?country=1');
$decode=json_decode($json);
回声“美国:”.$decode->kt代码>
$json=get_content('site.tld/api.php?country=2');
$decode=json_decode($json);
回声“巴西:”.$decode->kt代码>
但是大约有50多个参数,我认为这是一个非常糟糕的代码,但它确实有效。我怎样才能有效地做到这一点
谢谢。使用foreach()
循环,获取数组的键
/值
对,并使用它们动态显示数据
$countries = array(0 => 'Russia', 1 => 'USA', 2 => 'Brazil', 5 => 'Kazakhstan', /*and so on....*/);
// key is set in array and it equals value ex. 0 => "Russia"
或许
$countries = array('Russia', 'USA', 'Brazil', 'Kazakhstan', /*and so on....*/);
// key is not defined, yet exists and iterates starting at 0 then increments by 1 until the last key/value is reached inside the array
forloop($key=>value的数组){//遍历每个键/值对并收集数据}
$stmt = null; //create an empty variable to hold your content
// loop through the array and get the key/value --> $code/$country pairs
foreach($countries as $code => $country){
$json = get_content('site.tld/api.php?country='.$code); // Code is the key
$decode = json_decode($json);
$stmt .= $country.": ".$decode->kt."<br>"; // $country is the value
}
<?=$stmt?> <--or--> <?php echo $stmt; ?> // echo out result
$stmt=null//创建一个空变量来保存内容
//循环遍历数组并获取键/值-->$code/$country对
foreach($code=>$country的国家){
$json=get_content('site.tld/api.php?country='。$code);//代码是键
$decode=json_decode($json);
$stmt.=$country.:“$decode->kt.”
“;//$country是值
}
//回声输出结果
在阵列上循环怎么样?你怎么知道哪个数字是哪个国家的?@LewisBlundell我知道这些数据。这就是为什么我在上面给出了一个例子,我的意思是你可以做一个循环,但是我们需要知道数据是如何被安排的。除非我们知道这些国家的结构,否则我们无法将它们与数字进行匹配。您需要向我们提供更多数据信息,或者我们如何知道英格兰是3岁、12岁还是25岁?