[英]Check if any value in any 2 arrays with different dimension is same in php
我有 2 个数组 -
$arr1 =
Array
(
[0] => Array
(
[id] => 1
[sender_email] => test1@test.com
[to_email] => test@test.com
[description] => 5390BF675E1464F32202B
[created_at] => 2020-01-21 04:50:21
[status] => 1
)
[1] => Array
(
[id] => 30
[sender_email] => abcd@gmail.com
[to_email] => test@test.com
[description] => 729237A55E2EDCB80B18F
[created_at] => 2020-01-27 12:51:34
[status] => 1
)
[2] => Array
(
[id] => 31
[sender_email] => abc@gmail.com
[to_email] => test@test.com
[description] => 729237A55E2EDCB80B18F
[created_at] => 2020-01-27 12:51:34
[status] => 1
)
)
$arr2 =
Array
(
[0] => test1@test.com
[1] => abb@abb.com
[2] => abc@gmail.com
)
我试图从 $arr2 中找到 $arr1 中也存在的匹配值。
我试过
if(array_intersect($arr2, $arr1)) {
die('wrong');
}
但它显示错误,如 -
Notice: Array to string conversion in
我认为是由于结构不同。 如何做到这一点? 如果我可以在一个数组中获取所有匹配的值,那将非常有帮助。 列名将始终相同,但我要求不要将其包含在代码中。
这应该有效:
$matches = []; // array which will contains matches
foreach($arr1 as &$el){ // loop through the elements
if(array_intersect($arr2,$el)) array_push($matches, $el); //and if there is at least one elements as intersect of the two arrays, add it
}
这个递归函数循环遍历每个深度的所有元素并搜索$needle
的元素。 它returns an array with all matched values
:
function array_search_recursive( $needle, $haystack, $strict = false, &$matches = array() ) {
foreach( $haystack as $value ) {
if( is_array( $value ) ) {
array_search_recursive( $needle, $value, $strict, $matches );
} else {
if( in_array( $value, $needle, $strict ) ) {
$matches[] = $value;
}
}
}
return $matches;
}
// Parameters
// $needle: The array containing the searched values
// $haystack: The array to search in
// $strict: If it is set to true, it will also perform a strict type comparison
// $matches: Is only needed for recursion
用法:
$haystack = array(
array(
'id' => 1,
'email' => 'test@mail.de'
),
array(
'id' => 2,
'email' => 'mymail@web.de'
),
);
$needle = array( 'mymail@web.de', 1, 'lala@web.de' );
$matches = array_search_recursive( $needle, $haystack );
value of $matches
的value of $matches
:
Array
(
[0] => 1
[1] => mymail@web.de
)
array_intersect()
函数比较两个(或多个)数组的值,并返回匹配项。
此函数比较两个或多个数组的值,并返回一个数组,该数组包含 array1 中存在于 array2、array3 等中的条目。
$arr1 = array("alpha","omega","bravo","charlie","delta","foxfrot");
$arr2 = array("alpha","gamma","bravo","x-ray","charlie","delta","halo","eagle","foxfrot");
$result = array_intersect($arr1, $arr2);
print_r($result);
比较三个数组的值,并返回匹配项:
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");
$result=array_intersect($a1,$a2,$a3);
print_r($result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.