Question

I am trying to get the difference of two files:

$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);

The content of lalala.json is:

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

while the content of alabala.json is

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

However the problem is that I get an error, because the content will not be recognised as an array (the error is Argument #1 is not an array). If I do array_diff($first, $second) the output will be the content of $first which is

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

How should I handle this?

Was it helpful?

Solution

You need to convert the JSON objects to arrays first and then find the difference between the two arrays. To convert a JSON string into an array use json_decode() with true as second parameter:

$firstArray = json_decode($first, true);

If you leave the second parameter out, $firstArray would be an object, that is an instance of stdClass.

But first you'd need the content of the file as a string, so better use file_get_contents():

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

Update:
Even when you've converted the JSON strings properly into array, you'll still have a problem, as array_diff() only works with one dimensional arrays, as it's mentioned in the Notes section of the documentation. To be able to use in on multidimensional arrays, have a look at this comment to the documentation.

OTHER TIPS

You probably mean

$first = json_decode(file_get_contents('lalala.json'), true);
$second = json_decode(file_get_contents('alabala.json'), true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top