可能重复:
How to remove duplicate values from a multi-dimensional array in PHP
很抱歉写这个太快了,我正在工作......,对不起。现在我认为是很好的解释。我想删除子元素[title]常见,等于,我只想要一个元素,而不是重复,我怎么能这样做?我做到了,但我认为必须是一种更优雅的方式。我试过这段代码:
static function remove_duplicates_titles($deals){
$result = array();
$deal_repeated=false;
foreach ($deals as $index=>$deal) {
foreach ($deals as $deal_2) {
//discover if the subarray has the element title repeated is repeated or not
if ($deal['title'] == $deal_2['title']){
$deal_repeated=true;
unset($deal_2);
}
else{
$deal_repeated=false;
}
}
//if the array has no the element (title) repeated with another....
if(!$deal_repeated){
$result[]=$deal;
}
}
return $result;
}
Array
(
[0] => Array
(
[id] => abc
[title] => bbb
)
[1] => Array
(
[id] => ghi
[title] => aaa
)
[2] => Array //I should to remove this subarray (or the other, only one of both)
(
[id] => mno
[title] => pql //this is common
)
[3] => Array
(
[id] => abc
[title] => def
)
[4] => Array
(
[id] => ghi
[title] => mmm
)
[5] => Array //I should to remove this subarray (or the other), only one of both
(
[id] => mno
[title] => pql //this is common
)
)
答案 0 :(得分:3)
此功能将保留它找到的FIRSTS元素,并根据您提供的密钥删除任何重复
$arr = Array (
Array ( 'id' => 'abc', 'title' => 'bbb' ),
Array ( 'id' => 'ghi', 'title' => 'aaa' ),
Array ( 'id' => 'mno', 'title' => 'pql' ),
Array ( 'id' => 'abc', 'title' => 'def' ),
Array ( 'id' => 'ghi', 'title' => 'mmm' ),
Array ( 'id' => 'ere', 'title' => 'pql' )
);
function arrayUniqueFromKey(array $arr,$key)
{
$titles = array();$ret = array();
foreach ($arr as $v) {
if (!in_array($v[$key],$titles)) {
$titles[] = $v[$key];
$ret[] = $v;
}
}
return $ret;
}
print_r(arrayUniqueFromKey($arr,'title'));
答案 1 :(得分:1)
foreach($array as $key => $val) {
if (is_array($val)) {
foreach($array as $key2 => $val2) {
if($val['id']==$val2['id'] || $val['title']==$val2['title'])
{
unset($array[$key]);
break;
}
}
}
}