Home > Backend Development > PHP Tutorial > 新手!PHP关于两个数组对比!

新手!PHP关于两个数组对比!

WBOY
Release: 2016-06-23 13:45:33
Original
1371 people have browsed it

现在有两个数组:

A数组是从以产品ID为准到数据库获取过来的产品属性

B数组是页面提交过来的产品属性

两个数组对比,以A数组为基准,如果B数组比A数组少了一个元素,则删除数据库里面的这个元素关联ID!

如果B数组比A数组多了一个元素,则在数据库里面里面添加这个元素和关联ID

求教大神!!!


回复讨论(解决方案)

B 比 A 多出的项 array_diff(B, A)
A 比 B 多出的项 array_diff(A, B)

//B数组比A数组少了一个元素$a=array('a1','a2','a3','a4');$b=array('a1','a2','a3');$new=array_merge(array_diff($a, array_intersect($a, $b)), array_diff($b, array_intersect($a, $b)));echo "<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">";print_r($new);echo "
Copy after login
Copy after login
";/*Array( [0] => a4)*///B数组比A数组多了一个元素$a=array('a1','a2','a3');$b=array('a1','a2','a3','b1','b2');$new=array_merge(array_diff($a, array_intersect($a, $b)), array_diff($b, array_intersect($a, $b)));echo "
";print_r($new);echo "
Copy after login
";/*Array( [0] => b1 [1] => b2)*/
用$new数组跟$a数组对比,是增加还是删减就看你自己了

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template