我是PHP新手。我想在不使用array_diff()
或in_array()
等任何数组函数的情况下找到数组差异。
这是我的代码
$a = array('a','b','c','d','k');
$b = array('g','h','i','b','a','d','c');
$match = array();
$miss_match = array();
$count_a = count($a);
$count_b = count($b);
for($i=0; $i<$count_a;$i++)
{
for($j=0; $j<$count_b;$j++)
{
if($a[$i]==$b[$j])
{
$match[] = $a[$i];
break;
}
else
{
$miss_match[] = $b[$j];
}
}
}
print_r($match).'<br />';
print_r($miss_match);
我得到了这个结果
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [0] => g [1] => h [2] => i [3] => b [4] => g [5] => h
[6] => i [7] => g [8] => h [9] => i [10] => b [11] => a [12] => d
[13] => g [14] => h [15] => i [16] => b [17] => a [18] => g
[19] => h [20] => i [21] => b [22] => a [23] => d [24] => c )
我的预期结果是
数组([0] =&gt; g [1] =&gt; h [2] =&gt; i [3] =&gt; k)
请建议更好的解决方案。谢谢
答案 0 :(得分:1)
您将元素添加到miss_match
数组中,以用于与其不匹配的另一个数组的每个元素。但如果它与此元素不匹配,它可能仍然匹配后面的元素。
在确定它与任何数组都不匹配之前,您必须遍历整个数组。
for($i=0; $i<$count_a;$i++)
{
for($j=0; $j<$count_b;$j++)
{
$matched = false;
if($a[$i]==$b[$j])
{
$match[] = $a[$i];
$matched = true;
break;
}
}
if (!$matched)
{
$miss_match[] = $a[$i];
}
}
结果:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
Array
(
[0] => k
)
答案 1 :(得分:0)
这是我使用循环
查找数组差异的新代码$b = array('a','b','c','d','x','b');
$a = array('g','h','i','b','a','d','c');
$mismatch = array();
$count_a = count($a);
$count_b = count($b);
$match = array();
for( $i = 0; $i<count($a); $i++ )
{
$found_a ='no';
$foundss ='no';
for($j=0; $j<count($b); $j++ )
{
if($a[$i] == $b[$j])
{
$found_a ='yes';
$match[]=$a[$i];
}
}
if($found_a =='no')
{
for($t=0;$t<count($mismatch);$t++)
{
if($a[$i]== $mismatch[$t])
{
$foundss ='yes';
break;
}
}
if($foundss == 'no')
{
$mismatch[]=$a[$i];
}
}
}
for($z=0; $z< count($b); $z++)
{ $found_b ='no';
$found_match ='no';
for($t=0;$t<count($mismatch);$t++)
{
if($b[$z]==$mismatch[$t])
{
$found_b ='yes';
}
}
if($found_b =='no')
{
for($d =0; $d<count($match);$d++)
{
if($b[$z] ==$match[$d] )
{
$found_match='yes';
$break;
}
}
if($found_match=='no')
$mismatch[]=$b[$z];
}
}
print_r($mismatch);