PHP:数组索引中的 $variable 不返回结果
PHP: $variable in array index doesn't give back result
我有这个代码:
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = file_get_contents("http://ipinfo.io/myIp/country");
echo($names[$data]);
?>
$names
是国家代码数组,$data
是来自 IP 的国家代码,在我的例子中是:IE。我正在尝试输出完整的国家/地区名称,但由于某种原因它不起作用。但是,如果我输入: echo($names['IE']);
它工作正常。怎么了?
试试这个方法,对我来说很好用:
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = json_decode(file_get_contents("http://ipinfo.io"));
echo($names[$data->country]);
此外,您可能想参考 http://ipinfo.io/developers 并了解为什么您可能没有得到您期望的结果
我认为 $data
包含一个空字符。 trim 将删除字符串两侧的所有空字符,此代码有效:
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = trim(file_get_contents("http://ipinfo.io/MyIP/country"));
echo($names[$data]);
?>
还按照@ElefantPhace 的建议使用JSON 更好
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = json_decode(file_get_contents("http://ipinfo.io/MyIP/json"));
echo($names[$data->country]);
?>
我有这个代码:
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = file_get_contents("http://ipinfo.io/myIp/country");
echo($names[$data]);
?>
$names
是国家代码数组,$data
是来自 IP 的国家代码,在我的例子中是:IE。我正在尝试输出完整的国家/地区名称,但由于某种原因它不起作用。但是,如果我输入: echo($names['IE']);
它工作正常。怎么了?
试试这个方法,对我来说很好用:
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = json_decode(file_get_contents("http://ipinfo.io"));
echo($names[$data->country]);
此外,您可能想参考 http://ipinfo.io/developers 并了解为什么您可能没有得到您期望的结果
我认为 $data
包含一个空字符。 trim 将删除字符串两侧的所有空字符,此代码有效:
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = trim(file_get_contents("http://ipinfo.io/MyIP/country"));
echo($names[$data]);
?>
还按照@ElefantPhace 的建议使用JSON 更好
<?php
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$data = json_decode(file_get_contents("http://ipinfo.io/MyIP/json"));
echo($names[$data->country]);
?>