如何从多维数组中删除重复的条目?

时间:2021-12-23 00:15:55

In the below array linked_article_id has value 3 two times but I want to remove one entry from this array (i.e I want only one unique linked_article_id value). I tried the below function but did't work for me:

在下面的数组中,linked_article_id的值为2两次,但我想从这个数组中删除一个条目(即我只想要一个唯一的linked_article_id值)。我尝试了以下功能,但对我不起作用:

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

Array:

Array ( [0] => Array ( [id] => 193 [linked_article_id] => 2 [article_id] => 1 [article_title] => Test header link [slug] => test-header-link )
        [1] => Array ( [id] => 195 [linked_article_id] => 3 [article_id] => 1 [article_title] => upload image test [slug] => upload-image-test ) 
        [2] => Array ( [id] => 197 [linked_article_id] => 4 [article_id] => 1 [article_title] => Adrenal Fatigue [slug] => arrowdesigns01-test ) 
        [3] => Array ( [id] => 200 [linked_article_id] => 9 [article_id] => 1 [article_title] => Recipe2 [slug] => recipe2 )
        [4] => Array ( [id] => 211 [linked_article_id] => 15 [article_id] => 1 [article_title] => New [slug] => new )
        [5] => Array ( [id] => 214 [linked_article_id] => 3 [article_id] => 1 [article_title] => upload image test [slug] => upload-image-test ) 
)

1 个解决方案

#1


3  

Serialization is used to compare if the entire arrays are indentical, not just one key.

序列化用于比较整个数组是否是缩进的,而不仅仅是一个键。

You can extract the array and index (which must be unique) by linked_article_id:

您可以通过linked_article_id提取数组和索引(必须是唯一的):

$input = array_column($input, null, 'linked_article_id');

If you really need to re-index after (optional):

如果你真的需要重新索引之后(可选):

$input = array_values(array_column($input, null, 'linked_article_id'));

I don't see how anyone could be running PHP < 5.5.0 now, but just in case:

我不知道现在有人如何运行PHP <5.5.0,但以防万一:

foreach($input as $v) {
    $result[$v['linked_article_id']] = $v;
}

Then if needed:

然后如果需要:

$result = array_values($result);

#1


3  

Serialization is used to compare if the entire arrays are indentical, not just one key.

序列化用于比较整个数组是否是缩进的,而不仅仅是一个键。

You can extract the array and index (which must be unique) by linked_article_id:

您可以通过linked_article_id提取数组和索引(必须是唯一的):

$input = array_column($input, null, 'linked_article_id');

If you really need to re-index after (optional):

如果你真的需要重新索引之后(可选):

$input = array_values(array_column($input, null, 'linked_article_id'));

I don't see how anyone could be running PHP < 5.5.0 now, but just in case:

我不知道现在有人如何运行PHP <5.5.0,但以防万一:

foreach($input as $v) {
    $result[$v['linked_article_id']] = $v;
}

Then if needed:

然后如果需要:

$result = array_values($result);