1

I have two associative arrays:

$indexedProducts =

[0] => Array
    (
        [id] => 6662
    )

[1] => Array
    (
        [id] => 6656
    )

[2] => Array
    (
        [id] => 6657
    )

[3] => Array
    (
        [id] => 6527
    )

[4] => Array
    (
        [id] => 6528
    )

[5] => Array
    (
        [id] => 6529
    )

and $categoryProducts =

[0] => Array
    (
        [id] => 6527
    )

[1] => Array
    (
        [id] => 6528
    )

[2] => Array
    (
        [id] => 6529
    )

i am then running this command:

$difference = array_diff($indexedProducts[0], $categoryProducts[0]);

the result i am expecting from this is an array of the values 6662,6656 and 6657:

[0] => Array
    (
        [id] => 6662
    )

[1] => Array
    (
        [id] => 6656
    )

[2] => Array
    (
        [id] => 6657
    )

as these all occur in the first array and not in the second array.

The result i am receiving from this is

[id] => 6662

it seems to be stopping at the first index not found.

Where am i going wrong with this?

vmp
  • 271
  • 1
  • 3
  • 13

2 Answers2

3

What you actually need to diff on is the ID column in both multi arrays:

array_diff(
    array_column($indexedProducts, 'id'),
    array_column($categoryProducts, 'id')
);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
2

Array_diff only works on flat arrays.

Use array_column to make the arrays flat before diff-ing them.

var_dump(array_diff(array_column($indexedProducts, "id"), array_column($categoryProducts, "id")));
//[6662,6656,6657]

https://3v4l.org/5fsLE

Andreas
  • 23,610
  • 6
  • 30
  • 62