Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - Using array_intersect on a multi-dimensional array

I have two arrays that both look like this:

Array
(
    [0] => Array
        (
            [name] => STRING
            [value] => STRING
        )

    [1] => Array
        (
            [name] => STRING
            [value] => STRING
        )

    [2] => Array
        (
            [name] => STRING
            [value] => STRING
        )
)

and I would like to be able to replicate array_intersect by comparing the ID of the sub arrays within the two master arrays. So far, I haven't been successful in my attempts. :(

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use array_uintersect() to use a custom comparison function, like this:

$arr1 = array(
           array('name' => 'asdfjkl;', 'value' => 'foo'),
           array('name' => 'qwerty', 'value' => 'bar'),
           array('name' => 'uiop', 'value' => 'baz'),
        );

$arr2 = array(
           array('name' => 'zxcv', 'value' => 'stuff'),
           array('name' => 'asdfjkl;', 'value' => 'foo'),
           array('name' => '12345', 'value' => 'junk'),
           array('name' => 'uiop', 'value' => 'baz'),
        );

$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);

function compareDeepValue($val1, $val2)
{
   return strcmp($val1['value'], $val2['value']);
}

which yields, as you would hope:

Array
(
    [0] => Array
        (
            [name] => asdfjkl;
            [value] => foo
        )

    [2] => Array
        (
            [name] => uiop
            [value] => baz
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...