-2

Recently, I encountered some problem on comparing 2 nested arrays. I have tested to use array_diff_assoc to compare 2 arrays but it return me incorrect. Below are couple scenarios that I am attempt to compare these 2 nested array in php.

$arr1 = ["colorFamily"=>[]];
$arr2 = ["colorFamily"=>["blue","black"]];
$diff = array_diff_assoc($arr1,$arr2);

The $diff is expected to return below;

["colorFamily"=>[]]

Unfortunately, it return below:

[]

Aside from that, there are more complex scenario will be used in the comparison such as

$arr1 = ["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"],["value"=>"apple"]]];
$arr2 = ["colorFamily"=>["blue","black"],"descriptionMeasurement"=>[["label"=>"orange"]]];

Above scenario, it should return

["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"]]].

In short, anything occurs in $arr1 and it is not occurs in $arr2, should return in the $diff array. I hope you guys can help me to resolve this problem, I have been stucking for weeks.

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Miracle Hades
  • 146
  • 2
  • 10

1 Answers1

0

With array_diff you should always put the array with the missing values first, otherwise it doesn't return anything.

Also it can't see past the first array. So something like this will work:

$diff = array_diff_assoc($arr2["colorFamily"], $arr1["colorFamily"])

You could also use the following. array_map is used to index the keys:

$missing = array_map('unserialize', array_diff(array_map('serialize', $arr2), array_map('serialize', $arr1)));

(credits: Use array_diff_assoc() or get difference of multidimensional arrays)

hixlax
  • 31
  • 5
  • Hi, my scenario comparison can be n-tier multidimensional array. I have tested your solution but it does statisfy what I am looking. – Miracle Hades Jun 25 '21 at 13:57
  • Ah shame. Maybe you should loop though them instead of using array_diff, because it has quite limited usecases – hixlax Jun 25 '21 at 14:02