欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php多维数组去重,该如何解决

程序员文章站 2023-12-29 18:24:16
...
php多维数组去重
php多维数组去重,怎样去掉name为a的多余的那一个呢?
Array
(
[0] => Array
(
[id] => 79
[name] => a
)

[1] => Array
(

[id] => 79
[name] => a
)
[2] => Array
(
[id] => 78
[name] => b
)
[3] => Array
(

[id] => 36
[name] => c
)
)
------解决思路----------------------
$ar = array (
0 =>
array (
'id' => '79',
'name' => 'a',
),
1 =>
array (
'id' => '79',
'name' => 'a',
),
2 =>
array (
'id' => '78',
'name' => 'b',
),
3 =>
array (
'id' => '36',
'name' => 'c',
),
);
foreach($ar as $k=>$f) {
foreach($ar as $p=>$t) if($k != $p && $f == $t) unset($ar[$k]);
}
print_r($ar);
Array
(
[1] => Array
(
[id] => 79
[name] => a
)

[2] => Array
(
[id] => 78
[name] => b
)

[3] => Array
(
[id] => 36
[name] => c
)

)


------解决思路----------------------

$arr=array(
0=>array(
'id'=>79,
'name'=>'a'
),
1=>array(
'id'=>79,
'name'=>'a'

),
2=>array(
'id'=>78,
'name'=>'b'
),
3=>array(
'id'=>36,
'name'=>'c'
),
);
$item=array();
foreach($arr as $k=>$v){
if(!isset($item[$v['id']])) $item[$v['id']]=$v;
}
print_r(array_values($item));


Array
(
[0] => Array
(
[id] => 79
[name] => a
)

[1] => Array
(
[id] => 78
[name] => b
)

[2] => Array
(
[id] => 36
[name] => c
)

)



------解决思路----------------------


$ar = array (
0 =>
array (
'id' => '79',
'name' => 'a',
),
1 =>
array (
'id' => '79',
'name' => 'a',
),
2 =>
array (
'id' => '78',
'name' => 'b',
),
3 =>
array (
'id' => '36',
'name' => 'c',
),
);


$temp =array();
$result =array();

foreach($ar as $item){
$temp[] = json_encode($item);
}

$temp = array_unique($temp);

foreach($temp as $item){
$result[] = json_decode($item,true);
}

var_dump($result);

只是提供新思路 效率不高 勿用



array(3) {
[0]=>
array(2) {
["id"]=>
string(2) "79"
["name"]=>
string(1) "a"
}
[1]=>
array(2) {
["id"]=>
string(2) "78"
["name"]=>
string(1) "b"
}
[2]=>
array(2) {
["id"]=>
string(2) "36"
["name"]=>
string(1) "c"
}
}

------解决思路----------------------
SELECT DISTINCT(`id`) AS `id` , name FROM `TABLE`
php多维数组去重,该如何解决

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频


上一篇:

下一篇: