我试图从这两个json中获取返回的结果,并比较差异,仅显示唯一的值。我已经尝试了许多其他的方法,但似乎都没有效果。这段代码告诉我参数#1不是一个数组…有什么能帮我的吗?
<?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");
$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);
$result = array_diff($array1, $array2);
echo $result ;
?>
现在的结果是'数组',但我知道有差异....是否有一些方法来比较只是一个字段在返回的json数据…在这个实例中,com-name?
您的变量是字符串(url)而不是JSON。您正在尝试json_decode一个url!
如果我访问url,我得到XML…不是JSON。
- 您需要使用
file_get_contents()
从这些url获取数据。 - 您需要将
true
作为第二个参数传递给json_decode
以获得数组结果:
.
$xml = file_get_contents('http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&format=json');
$xml2 = file_get_contents('http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&format=json');
$array1 = json_decode($xml, true);
$array2 = json_decode($xml2, true);
您所做的实际上是试图解码URL ADDRESSES到JSON格式,而不是在这些特定URL地址中找到的内容。为了JSON解码内容而不是URL本身,您可以使用以下代码:
$content = file_get_contents($xml); //get the content that is found in the url that $xml holds
$json = json_decode($content); //now json decode the content , and not the url itself
我希望它能帮助你理解你做错了什么。使用file_get_contents()和json_decode()函数是比较容易的部分,首先您必须规划代码实际应该做什么。好运。 正如上面的海报所说,您将需要实际检索文件。只是调用json_decode将只是尝试解码JSON字符串,这根本不是你想要实现的。