尝试一些自定义数组差异,如 PHP 中的方法

$a = ["a","b","c","a","b"];

$b = ["a","c"];

array_diff($a,$b);

//output will be [b,b]

但这不是一个适当的区别,它也可以是


//output [b,a,b]  <- this is what I am trying to achieve

我尝试了 foreach 循环和 for 循环,但未能得到它...


我试过的 Foreach 例子


$a = ["a","b","c","a","b"];

$b = ["a","c"];

echo array_diff_custom($a,$b),"<br>";


function array_diff_custom($a,$b){

$result =0;

    foreach($a as $key=>$val){

        foreach($b as $key2=>$val2){

                  if($val == $val2){

                     unset($a[$key]);

                   }         


        }


    }

$result = count($a);

return $result;

}



echo array_diff_custom($b,$a);

for 循环示例,我试过了


$a = ["a","b","c","a","b"];

$b = ["a","c"];

echo array_diff_custom($a,$b),"<br>";


function array_diff_custom($a,$b){

$result =0;

    for($i=0;$i<count($a);$i++){

        for($j=0;$j<count($b);$j++){

                 //echo $a[$i]."-".$b[$j]."<br>";

                  if($a[$i] == $b[$j]){

                     unset($a[$i]);

                   }         


        }


    }

$result = count($a);

return $result;

}



echo array_diff_custom($b,$a);

我使用count($resut)的功能,例如我创建,但你可以只是简单的return $a和可print_R(array_Diff_custom) 检查输出...


慕的地6264312
浏览 163回答 1
1回答

aluckdog

您可以仅从第一个数组中取消设置第二个数组中显示的项目一次function array_diff_custom($a,$b){&nbsp; foreach($b as $x){&nbsp; &nbsp; if($k = array_keys($a, $x)) {&nbsp; &nbsp; &nbsp; &nbsp; unset($a[$k[0]]);&nbsp; &nbsp; }&nbsp; }&nbsp; return $a;}print_r(array_diff_custom($a,$b));&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP