当前位置:Gxlcms > PHP教程 > 多次foreach循环结果去重

多次foreach循环结果去重

时间:2021-07-01 10:21:17 帮助过:24人阅读

$a=array(0 =>array([logo] => Array
(
[id] =>1
[sid] => 6
)
1=>array([logo] => Array
(
[id] =>2
[sid] => 6
)
)
使用foreach循环$a,只显示不同的SID;


回复讨论(解决方案)

贴出经var_export() 运行后的数组出来

$last = 0;foreach($a as $r) {  foreach($r as $v) {    if($last != $v['sid']) echo $v['sid'];    $last = $v['sid'];  }}

array ( 0 => array ( 'logo' => array ( 'id' => 1, 'sid' => 6, ), ), 1 => array ( 'logo' => array ( 'id' => 2, 'sid' => 6, ), ), )

$res = array();foreach($a as $v){	if(!isset($res[$v['logo']['sid']])) $res[$v['logo']['sid']] = $v;}print_r(array_values($res));

$last = 0;foreach($a as $r) {  foreach($r as $v) {    if($last != $v['sid']) echo $v['sid'];    $last = $v['sid'];  }}


刚刚测试了下,表示您给的代码有点缺陷,改良了下:
$i ='';
foreach($a as $r=>$v){
foreach($v as $k=>$vv){
if(!stristr($i,$vv['sid'])) {
$i .= $vv['sid'];
echo $vv['sid']; } } }应该没有什么问题了

$res = array();foreach($a as $v){	if(!isset($res[$v['logo']['sid']])) $res[$v['logo']['sid']] = $v;}print_r(array_values($res));


可能我问题说的不清楚,不过还是解决了,主要是去掉同一字段的重复的结果。

人气教程排行