php 在多维数组上使用 array_intersect

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5653241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:07:01  来源:igfitidea点击:

Using array_intersect on a multi-dimensional array

phparraysmultidimensional-arrayarray-intersect

提问by Nathan

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

我希望能够通过比较两个主阵列中子阵列的 ID 来复制 array_intersect。到目前为止,我的尝试还没有成功。:(

回答by Wiseguy

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

使用array_uintersect()使用自定义的比较函数,就像这样:

$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
        )

)

回答by ScreamZ

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.

确保 val2 键存在于 val1 数组中,因为该函数首先对数组进行排序。很奇怪。

回答by rüff0

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

您可以将嵌入式函数与 array_uintersect php 函数一起使用。前任:

$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)