Home > Backend Development > PHP Tutorial > 多次foreach循环结果去重

多次foreach循环结果去重

WBOY
Release: 2016-06-20 12:30:26
Original
2311 people have browsed it

$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'];  }}
Copy after login
Copy after login

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));
Copy after login
Copy after login

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


刚刚测试了下,表示您给的代码有点缺陷,改良了下:
$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));
Copy after login
Copy after login
 


可能我问题说的不清楚,不过还是解决了,主要是去掉同一字段的重复的结果。
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