欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP数组比较有关问题

程序员文章站 2022-05-05 13:47:36
...
PHP数组比较问题

$ar1=array(array('id'=>1,"name"=>"张1","sign"=>""),array('id'=>2,"name"=>"张2","sign"=>""),array('id'=>5,"name"=>"张5","sign"=>""));
$ar2=array(array('id'=>1,"name"=>"张1"),array('id'=>2,"name"=>"张2"));


如果ar2的id与ar1的id相同,那么ar1的sign则复制给1,否则不赋值,怎么解决?
------解决思路----------------------
$ar1=array(array('id'=>1,"name"=>"张1","sign"=>""),array('id'=>2,"name"=>"张2","sign"=>""),array('id'=>5,"name"=>"张5","sign"=>""));
$ar2=array(array('id'=>1,"name"=>"张1"),array('id'=>2,"name"=>"张2"));

//先将 $ar2 规格化一下
foreach($ar2 as $v) $r[$v['id']] = $v;
$ar2 = $r;

//接下来就简单了
foreach($ar1 as &$v) {
if(isset($ar2[$v['id']])) $v['sign'] = 1;
}

print_r($ar1);
Array
(
[0] => Array
(
[id] => 1
[name] => 张1
[sign] => 1
)

[1] => Array
(
[id] => 2
[name] => 张2
[sign] => 1
)

[2] => Array
(
[id] => 5
[name] => 张5
[sign] =>
)

)

PHP数组比较有关问题

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频