如何从array_intersect()获得区分大小写的返回

时间:2023-01-14 12:12:21

I have two arrays and I need to compare that and return matched value from array1. Please refer my code below,

我有两个数组,我需要比较它并从array1返回匹配的值。请参考下面的代码,

$array1 = array("a" => "Green", "Red", "Blue");
$array2 = array("b" => "grEEn", "yellow", "red");
$result = array_intersect(array_map('strtolower', $array1), array_map('strtolower', $array2));

print_r($result);

My result is,

我的结果是,

Array
(
    [a] => green
    [0] => red
)

But my expected result is I want get it from array1 like:

但我期望的结果是我想从array1得到它像:

Array
(
    [a] => Green
    [0] => Red
)

1 个解决方案

#1


This is because you put all values to lowercase. Just change to array_uintersect() and use strcasecmp() as callback function to compare them case-insensitive, like this:

这是因为您将所有值都设置为小写。只需更改为array_uintersect()并使用strcasecmp()作为回调函数来比较它们不区分大小写,如下所示:

$result = array_uintersect($array1, $array2, "strcasecmp");

output:

Array ( [a] => Green [0] => Red )

#1


This is because you put all values to lowercase. Just change to array_uintersect() and use strcasecmp() as callback function to compare them case-insensitive, like this:

这是因为您将所有值都设置为小写。只需更改为array_uintersect()并使用strcasecmp()作为回调函数来比较它们不区分大小写,如下所示:

$result = array_uintersect($array1, $array2, "strcasecmp");

output:

Array ( [a] => Green [0] => Red )