Home  >  Article  >  Backend Development  >  php【数组对比输出】解决办法

php【数组对比输出】解决办法

WBOY
WBOYOriginal
2016-06-13 12:16:57798browse

php【数组对比输出】

<br />$array1=array("1","2","3","4","5","6");//此数据值固定。<br />$array2=array("1","3","6","4");//此数据值不固定。<br />

实现效果:
array2与array1对比后array2没有的值用0代替。
结果:
1,0,3,4,0,6

请问怎么实现
------解决思路----------------------
<br />$arr = array();<br />$x;<br />foreach($array2 as $k => $v) {<br />    x = array_search($v,$array1);<br />     if (x) {<br />        $arr[$k] = $v;<br />    } else {<br />        $arr[$k] = 0;<br />    }<br />}<br />

------解决思路----------------------
$array1=array("1","2","3","4","5","6");//此数据值固定。<br />$array2=array("1","3","6","4");//此数据值不固定。<br />$arr = array();<br />foreach($array1 as $v){<br />	$arr[] = in_array($v, $array2) ? $v : 0;<br />}<br />print_r($arr);

------解决思路----------------------

引用
#1
$arr = array();
$x;
foreach($array2 as $k => $v) {
    x = array_search($v,$array1);
     if (x) {
        $arr[$k] = $v;
    } else {
        $arr[$k] = 0;
    }
}

array_search()返回的是匹配到的键名,当第一个匹配到,键名是0,if判断就不存在了,这里存在一点问题
------解决思路----------------------
php里面有个数组比较函数 array_diff的呀。
------解决思路----------------------
不错,可以借助 array_diff
$a = array("1","2","3","4","5","6");<br />$b = array("1","3","6","4");<br />$c = $a;<br />foreach(array_diff($a, $b) as $k=>$v) $c[$k] = 0;<br /><br />print_r($c);
Array<br />(<br />    [0] => 1<br />    [1] => 0<br />    [2] => 3<br />    [3] => 4<br />    [4] => 0<br />    [5] => 6<br />)<br /><br />

------解决思路----------------------
<br />$array1=array("1","2","3","4","5","6");//此数据值固定。<br />$array2=array("1","3","6","4");//此数据值不固定。<br />
$c = array_diff($array1, $array2);

foreach($c as $k=>$v){
$array1[$k] = 0;
}

print_r($array1);


Array
(
    [0] => 1
    [1] => 0
    [2] => 3
    [3] => 4
    [4] => 0
    [5] => 6
)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:为什么这么写不行呢Next article:这句怎么理解