php按值从多维数组中删除重复项

标签 php arrays multidimensional-array

<分区>

我想按值删除重复项,如您在 list_title 中所见。我知道有几个问题和答案,但他们的解决方案对我不起作用。

这是我尝试过的:

$uniqueArray = array_map("unserialize", array_unique(array_map("serialize", $notify)));

结果:

Array
(
[0] => Array
    (
        [list_id] => 86
        [list_reference] => 130948
        [list_title] => Offer:  apartment 2+kk 
        [list_city] => Prague
        [list_date] => 2017-03-03 11:20:35
        [list_status] => 0
        [list_creator] => Company A
        [list_price] => 30000
        [list_furniture] => ["1","0","0"]
        [list_accommodation] => flat
    )

[1] => Array
    (
        [list_id] => 87
        [list_reference] => 130947
        [list_title] => Offer:  apartment 2+kk 
        [list_date] => 2017-03-03 11:20:35
        [list_status] => 0
        [list_creator] => Company B
        [list_price] => 30000
        [list_furniture] => ["1","0","0"]
        [list_accommodation] => flat
    )

[2] => Array ...

预期结果应该是其中之一,因为标题:

Array
(
[0] => Array
(
    [list_id] => 86
    [list_reference] => 130948
    [list_title] => Offer:  apartment 2+kk 
    [list_city] => Prague
    [list_date] => 2017-03-03 11:20:35
    [list_status] => 0
    [list_creator] => Company A
    [list_price] => 30000
    [list_furniture] => ["1","0","0"]
    [list_accommodation] => flat
)

最佳答案

所以基本上你想通过 'list_title' 列删除重复项。让我们假设我们保留这个标题的第一次出现。然后您可以使用几个标准函数来实现此目的:

// Reverse array, so the first occurrence kept.
$data = array_reverse($data);

$result = array_reverse( // Reverse array to the initial order.
    array_values( // Get rid of string keys (make array indexed again).
        array_combine( // Create array taking keys from column and values from the base array.
            array_column($data, 'list_title'), 
            $data
        )
    )
);

这里是 working demo .

更新:

根据@mickmackusa 的评论,代码可以简化为:

$result = array_reverse(array_values(array_column(
    array_reverse($data),
    null,
    'list_title'
)));

这在 the docs 中有描述关于 column_key 参数规范:

It may also be NULL to return complete arrays or objects (this is useful together with index_key to reindex the array).

关于php按值从多维数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577258/

相关文章:

php - 如何执行ajax函数onbeforeunload?

Javascript 将未知名称函数插入数组

c++ - 具有静态 std::array 的神经网络比使用动态 C 数组的神经网络慢

PHP 7 - 如何搜索数组的多个特定成员

c - 如何将 3D 数组从 C 返回到 Java?

php - 在网站输出后使用 header() 和 setCookie() 等函数

php - Facebook PHP SDK - 需要在特定帐户上登录

php - L5 随机 TokenMismatchExceptions

c++ - 将文件的列读入数组

javascript - 跳过每个()中的第一个元素?