我有两个多维数组:
草堆
$haystack = array (
0 => array (
"child_element_id" => 11
"answer_id" => 15
),
1 => array (
"child_element_id" => 12
"answer_id" => 17
),
2 => array (
"child_element_id" => 13
"answer_id" => 21
)
)
针
$needle = array (
0 => array (
"child_element_id" => 12
"answer_id" => 17
),
1 => array (
"child_element_id" => 13
"answer_id" => 21
)
)
我想检查数组“Needle”中的所有键值是否都存在于数组“Haystack”中。这是最好的做法是什么?谢谢!
答案 0 :(得分:2)
几乎是一个解决方案:
@shalvah给了一个很好的起点。但是,在建议的解决方案中,他忘了循环遍历$needle
数组的元素,如下所示:
function array_in_array($neearr,$haystack) {
foreach ($neearr as $needle){
foreach ($haystack as $array) {
//check arrays for equality
if(count($needle) == count($array)) {
$needleString = serialize($needle);
$arrayString = serialize($array);
echo "$needleString||$arrayString<br>";
if(strcmp($needleString, $arrayString) == 0 ) return true;
}
return false;
}
}
}
但即便如此,这并非完全“防水”。如果“needle”数组的元素以不同的顺序(序列)出现,serialze()
- 函数将产生不同的字符串并导致错误否定,如下例所示:
$hay=array(array('a'=>'car','b'=>'bicycle'),
array('a'=>'bus','b'=>'truck'),
array('a'=>'train','b'=>'coach'));
$nee1=array(array('a'=>'car','b'=>'bicycle'),
array('a'=>'train','b'=>'coach'));
$nee2=array(array('b'=>'bicycle','a'=>'car'), // different order of elements!
array('a'=>'train','b'=>'coach'));
echo array_in_array($nee1,$hay); // true
echo array_in_array($nee2,$hay); // false (but should be true!)
稍微好一点的解决方案
这个问题可以通过首先排序(ksort()
:按键值排序)serialize
之前所有“针”数组的所有元素来解决:
function array_in_array($neearr,$haystack) {
$haystackstrarr = array_map(function($array){ksort($array);return serialize($array);},$haystack);
foreach ($neearr as $needle){
ksort($needle);
$needleString = serialize($needle);
foreach ($haystackstrarr as $arrayString){
if(strcmp($needleString, $arrayString) == 0 ) return true;
}
return false;
}
}
echo array_in_array($nee1,$hay); // true
echo array_in_array($nee2,$hay); // true
答案 1 :(得分:1)
您可以使用此功能:
function array_in_array(array $needle, array $haystack) {
foreach($needle as $nearr) {
foreach ($haystack as $array) {
//check arrays for equality
if(count($needle) == count($array)) {
$needleString = serialize($needle);
$arrayString = serialize($array);
if(strcmp($needleString, $arrayString) == 0 )
return true;
}
}
return false;
}
答案 2 :(得分:1)
使用in_array()
非常简单,因为needle可以是一个数组:
$found = 0;
foreach($needle as $array) {
if(in_array($array, $haystack, true)) {
$found++;
}
}
if($found === count($needle)) {
echo 'all needles were found in haystack';
}
或者也许:
$found = true;
foreach($needle as $array) {
if(!in_array($array, $haystack, true)) {
$found = false;
break;
}
}
if($found) {
echo 'all needles were found in haystack';
}
您甚至可以使用array_search()
,因为您也可以使用针阵列,不需要运行两个循环。
使用serialize()
:
if(count(array_map('unserialize',
array_intersect(array_map('serialize', $needle),
array_map('serialize',$haystack)))) == count($needle))
{
echo 'all needles were found in haystack';
}
serialize()
两个数组的内部数组并计算交集(公共内部数组)unserialize()
结果并将count()
与$needle