当前位置:Gxlcms > PHP教程 > PHP二维数组去除特定重复值的有关问题

PHP二维数组去除特定重复值的有关问题

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

【求助】PHP二维数组 去除特定重复值的问题
原数组:
$arr = array(
array('id' => 1,'name' => 'aaa','uid'=>1),
array('id' => 2,'name' => 'bbb','uid'=>2),
array('id' => 3,'name' => 'ccc','uid'=>3),
array('id' => 4,'name' => 'ddd','uid'=>4),
array('id' => 5,'name' => 'ccc','uid'=>3),
array('id' => 6,'name' => 'bbb','uid'=>2),
array('id' => 7,'name' => 'bbb','uid'=>2),
array('id' => 8,'name' => 'fff','uid'=>6),
array('id' => 9,'name' => 'ccc','uid'=>3),
array('id' => 10,'name' => 'bbb','uid'=>2),
array('id' => 11,'name' => 'ddd','uid'=>4),
array('id' => 12,'name' => 'eee','uid'=>5),
array('id' => 13,'name' => 'fff','uid'=>6),
);

问题描叙:想获取$arr中id为 1,3,5,7,9的值,但是‘name’和‘uid’的值不能有重复。举例:id==3对应的name==ccc,但是id==5对应的 name==ccc,所以不取id为5的这一条,取它的下一条 id=6的值,如果id=6的值,和前面的还有重复,则再取下一条,以此类推。

如果想要取id为1,3,5,7,9的值,则想要的结果是:
$arr_new = array(
array('id' => 1,'name' => 'aaa','uid'=>1),
array('id' => 3,'name' => 'ccc','uid'=>3),
array('id' => 6,'name' => 'bbb','uid'=>2),
array('id' => 8,'name' => 'fff','uid'=>6),
); PHP 二维数组递归取值

分享到:


------解决方案--------------------
这个是算法处理的方式有问题 他会遍历当前已经取的数据 然后如果查到已经有了 则取下一条 -- 这种算法的目的 是用来统计人数的 一个人发多张贴 也只算一个 如果要解决 只要把遍历当前查询的数据部分的代码注释即可
------解决方案--------------------
这个意思?
$arr = array( 
array('id' => 1,'name' => 'aaa','uid'=>1),
array('id' => 2,'name' => 'bbb','uid'=>2),
array('id' => 3,'name' => 'ccc','uid'=>3),
array('id' => 4,'name' => 'ddd','uid'=>4),
array('id' => 5,'name' => 'ccc','uid'=>3),
array('id' => 6,'name' => 'bbb','uid'=>2),
array('id' => 7,'name' => 'bbb','uid'=>2),
array('id' => 8,'name' => 'fff','uid'=>6),
array('id' => 9,'name' => 'ccc','uid'=>3),
array('id' => 10,'name' => 'bbb','uid'=>2),
array('id' => 11,'name' => 'ddd','uid'=>4),
array('id' => 12,'name' => 'eee','uid'=>5),
array('id' => 13,'name' => 'fff','uid'=>6),
);
$id = array(1,3,5,7,9);

foreach($arr as $v) $a[$v['id']] = $v;

$t = array();
foreach($id as $k) {
if(! in_array($a[$k]['name'], $t)) {
$res[] = $a[$k];
$t[] = $a[$k]['name'];
}else {
for($i=$k+1; $i if(! in_array($a[$i]['name'], $t)) {
$res[] = $a[$i];
$t[] = $a[$i]['name'];
break;
}
}
}
print_r($res);
Array
(
[0] => Array
(
[id] => 1
[name] => aaa
[uid] => 1
)

[1] => Array
(
[id] => 3
[name] => ccc
[uid] => 3
)

[2] => Array
(
[id] => 6
[name] => bbb
[uid] => 2

人气教程排行