"张1","sign"=>""),array('id'=>2,"name"=>"张2","sign"=>""),array('id'=>5,"name"=>"张5","sign"=>""));  &"/> "张1","sign"=>""),array('id'=>2,"name"=>"张2","sign"=>""),array('id'=>5,"name"=>"张5","sign"=>""));  &">

首頁 >後端開發 >php教程 >PHP数组比较有关问题

PHP数组比较有关问题

WBOY
WBOY原創
2016-06-13 12:17:47953瀏覽

PHP数组比较问题

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


如果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"=>""));<br />$ar2=array(array('id'=>1,"name"=>"张1"),array('id'=>2,"name"=>"张2"));<br /><br />//先将 $ar2 规格化一下<br />foreach($ar2 as $v) $r[$v['id']] = $v;<br />$ar2 = $r;<br /><br />//接下来就简单了<br />foreach($ar1 as &$v) {<br />  if(isset($ar2[$v['id']])) $v['sign'] = 1;<br />}<br /><br />print_r($ar1);<br />
Array<br />(<br />    [0] => Array<br />        (<br />            [id] => 1<br />            [name] => 张1<br />            [sign] => 1<br />        )<br /><br />    [1] => Array<br />        (<br />            [id] => 2<br />            [name] => 张2<br />            [sign] => 1<br />        )<br /><br />    [2] => Array<br />        (<br />            [id] => 5<br />            [name] => 张5<br />            [sign] => <br />        )<br /><br />)<br /><br />

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn