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

WBOY
Release: 2016-06-13 12:16:57
Original
804 people have browsed it

php【数组对比输出】

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

实现效果:
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 />
Copy after login

------解决思路----------------------
$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);
Copy after login

------解决思路----------------------
引用
#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);
Copy after login
Array<br />(<br />    [0] => 1<br />    [1] => 0<br />    [2] => 3<br />    [3] => 4<br />    [4] => 0<br />    [5] => 6<br />)<br /><br />
Copy after login

------解决思路----------------------
<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);
Copy after login


Array
(
    [0] => 1
    [1] => 0
    [2] => 3
    [3] => 4
    [4] => 0
    [5] => 6
)

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!