Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

php - array_diff() with multidimensional arrays

Using array_diff(), I can compare and remove similar items, but what if I have the following arrays?

Array1

Array
(
    [0] => Array
        (
            [ITEM] => 1
        )

    [1] => Array
        (
            [ITEM] => 2
        )

    [2] => Array
        (
            [ITEM] => 3
        )
)

Array2

Array
(
    [0] => Array
        (
            [ITEM] => 2
        )

    [1] => Array
        (
            [ITEM] => 3
        )

    [2] => Array
        (
            [ITEM] => 1
        )
    [3] => Array
        (
            [ITEM] => 4
        )
)

I want to filter out the similar items; result should return 4. How can I rearrange my array so that I can use array_diff()?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can define a custom comparison function using array_udiff().

function udiffCompare($a, $b)
{
    return $a['ITEM'] - $b['ITEM'];
}

$arrdiff = array_udiff($arr2, $arr1, 'udiffCompare');
print_r($arrdiff);

Output:

Array
(
    [3] => Array
        (
            [ITEM] => 4
        )
)

This uses and preserves the arrays' existing structure, which I assume you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...