Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

php删除数组中的重复数据,只留下没有重复的数据怎么实现?

array(
    0 =>array('attr_id' => '1','attr_name' => '颜色',),
    1 =>array('attr_id' => '3','attr_name' => '重量',),
    2 =>array('attr_id' => '4','attr_name' => '速度',),
    3 =>array('attr_id' => '1','attr_name' => '颜色',),
    4 =>array('attr_id' => '3','attr_name' => '重量',),
    5 =>array('attr_id' => '4','attr_name' => '速度',),
    6 =>array('attr_id' => '5','attr_name' => '力量',),
    7 =>array('attr_id' => '6','attr_name' => '型号',),
);

数组中重复的 attr_name 为 (颜色、重量、速度) 我要删除数组中的这些值,只留下 attr_name 为 (力量、型号) 的

如下效果

$arr = array(
    0 =>array('attr_id' => '5','attr_name' => '力量',),
    1 =>array('attr_id' => '6','attr_name' => '型号',),
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$map = [];
foreach ($arr as $v) {
    if(array_key_exists($v['attr_id'],$map)){
        $map[$v['attr_id']]++;
    }else{
        $map[$v['attr_id']]=1;
    }
}

$rs = [];
for ($i=0; $i < count($arr); $i++) { 
    if($map[$arr[$i]['attr_id']] == 1){
        array_push($rs,$arr[$i]);
    }
}

print_r($rs);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...