2013-05-09 18 views
1

我試圖讓兩個文件的區別:和array_diff在爭論未服用

$first = file('lalala.json'); 
$second = file('alabala.json'); 
//print_r($first); 
//print_r($second); 
$first_result = array_diff($first[0], $second[0]); 
//$second_result = array_diff($second, $first); 
print_r($first_result); 
//print_r($second_result); 

lalala.json內容是:

`[{"name":"Tim Pearson","id":"17118"},{"name":"Ashley Danchen Chen","id":"504829084"},{"name":"Foisor Veronica","id":"100005485446135"}]` 

alabala.json內容

`[{"name":"Tim Pearson","id":"17118"},{"name":"Foisor Veronica","id":"100005485446135"}]` 

但問題是我得到一個錯誤,因爲內容不會被重新認爲是一個數組(錯誤是Argument #1 is not an array)。如果我做array_diff($first, $second)輸出將是$first內容是

Array ([0] => [{"name":"Tim Pearson","id":"17118"},{"name":"Ashley Danchen Chen","id":"504829084"},{"name":"Foisor Veronica","id":"100005485446135"}]) 

我應該如何處理呢?

回答

0

您需要首先將JSON對象轉換爲數組,然後找到兩個數組之間的差異。要將JSON字符串轉換成一個陣列中使用json_decode()true作爲第二個參數:

$firstArray = json_decode($first, true); 

如果你離開了第二個參數,$ firstArray將是一個對象,那就是stdClass一個實例。

但首先你需要的文件作爲字符串的內容,所以最好使用file_get_contents()

$first = file_get_contents('lalala.json'); 

更新:
即使你已經轉換JSON字符串進行到數組,您仍然會遇到問題,因爲array_diff()僅適用於一維陣列,因爲它在文檔的Notes部分提及。要能夠在多維數組中使用,請查看文檔的this comment

+0

什麼真正的意思嗎?在這種情況下,當然 – 2013-05-09 13:34:32

+0

它會將字符串轉換爲數組而不是對象(stdClass的實例) – Havelock 2013-05-09 13:35:03

+0

但現在由於某種原因,輸出是一個空數組 – 2013-05-09 13:40:20

0

你大概的意思

$first = json_decode(file_get_contents('lalala.json'), true); 
$second = json_decode(file_get_contents('alabala.json'), true);