2013-04-09 67 views
-1

我试图从这两个json中获取返回的结果,并比较差异以仅显示唯一值。我尝试了许多其他方法,但似乎没有任何工作。此代码给我参数#1不是一个数组...任何帮助我在这里失踪?将json转换为数组并比较差异

<?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-的名字吗?

+0

严。你在说json,但你的变量名是$ xml和$ xml2? – 2013-04-09 15:35:49

+0

对不起,一直在用xml尝试它..我更新了代码 – 2013-04-09 15:55:35

回答

1

您的变量是字符串(网址)而不是JSON。 你正在尝试json_decode一个网址!

此外,如果我访问的网址,我得到的XML ...不是JSON。

+0

我看到我更新了url,所以现在它返回json-&fmt而不是&format。 – 2013-04-09 15:40:04

+0

+1为捕捉他们实际上并没有抓住这些数据。我忽略了这一点。 – 2013-04-09 15:42:30

+0

@JonathanCoffey没有。仍然给XML ...即使如此。你需要获取URL的内容,并尝试json_decode,而不是json_decoding自己的URL。尝试''xml = file_get_contents(“http:// blahblahblah”);''和'$ xml2 = file_get_contents(“http:// blahblahblah”);'一旦你找出正确的网址 – 2013-04-09 15:43:39

0
  1. 您需要使用file_get_contents()从这些URL中获取数据。
  2. 您需要通过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); 
0

你所做的实际上是试图将URL地址解码为JSON格式,而不是在这些特定的url地址中找到的内容。 为了JSON解码contnent,而非网址本身,你可以使用下面的代码:

$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()函数是很简单的部分,首先你必须计划你的代码实际上应该做什么。 祝你好运。

0

正如上面的海报所说,您将需要实际检索文件。只要调用json_decode就会尝试解码一个JSON字符串,这完全不是你想要实现的。