user2899728 user2899728 - 1 year ago 53
PHP Question

PHP: Why the array generated by array_udiff cannot be converted into valid json?

I am facing a very weird and uncommon issue in PHP.
I am using array_udiff for array of objects.
The array generated by array_udiff could not be converted into valid JSON format.

I created same same array ( that is equal to the array generated by array_udiff ) and then converted that array in JSON But this json structure was perfect exactly what I want.

I wrote an example in very detail to reproduce this issue:

$a = array( (object) array('id'=>1, 'name'=>'abc'), (object) array('id'=>2, 'name'=>'xyz'), (object) array('id'=>6, 'name'=>'Amber'));
$b = array( (object) array('id'=>3, 'name'=>'david'), (object) array('id'=>1, 'name'=>'abc'));

$c = array_udiff($a, $b, 'comp_func');

function comp_func($obj1, $obj2)
return $obj1->id-$obj2->id;

echo '<h1>Array Generated by array_udiff:</h1><br> ';

echo "<br><strong>Invalid JSON:</strong></br>";
echo json_encode($c);
echo "<br><br><br>";
echo '<h1>Manually created array:</h1><br> ';

$d = array( (object) array('id'=>2, 'name'=>'xyz'), (object) array('id'=>6, 'name'=>'Amber'));
echo "<br><strong>Invalid JSON:</strong></br>";
echo json_encode($d);


enter image description here

So as you can see in above example:
Both arrays printed by print_r has similar structure but when I tried to convert both them in JSON then JSON structure for both of arrays was different as seen in the screenshot.

I will appreciate any contribution.

Answer Source

Your array in array_udiff() is starting from index 1 which is why json_encode() is not able to encode the way you want. You can simply change this line:

$c = array_udiff($a, $b, 'comp_func');


$c = array_values(array_udiff($a, $b, 'comp_func'));

This will index the array from 0.