Using array_intersect on a multi-dimensional array

馋奶兔 提交于 2019-11-26 16:13:55

问题


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. :(


回答1:


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
        )

)



回答2:


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

Be sure that val2 key is existing in val1 array, because the function is ordering array first. Very strange.




回答3:


you can use embedded function with array_uintersect php function. ex:

$intersectNames = array_uintersect($arr1, $arr2, function ($val1, $val2){
    return strcmp($val1['name'], $val2['name']);
    });

$intersectValues = array_uintersect($arr1, $arr2, function ($val1, $val2){
    return strcmp($val1['value'], $val2['value']);
    });

print_r('namesIntersected' => $intersectNames, 'valuesIntersected' => $intersectValues)


来源:https://stackoverflow.com/questions/5653241/using-array-intersect-on-a-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!