删除值重复数组php

时间:2018-10-28 19:19:48

标签: php arrays

我有一个数组,需要删除它是否与from [id]重复项的值相同,我尝试这样做:

$comments_new = array_map ("unserialize", 
          array_unique (array_map ("serialize", $ comments)))

但是,没有变化。我的数组模板。

Array
(
    [0] => Array
        (
            [created_time] => 2018-10-28T17:35:58+0000
            [from] => Array
                (
                    [name] => Usuario
                    [id] => 111111
                )

            [message] =>test  as das
            [id] => 4234234214123412341234124
        )

    [1] => Array
        (
            [created_time] => 2018-10-28T17:35:24+0000
            [from] => Array
                (
                    [name] => Usuario2
                    [id] => 22222222
                )

            [message] => test
            [id] => 12341241234134444343
        )

    [2] => Array
        (
            [created_time] => 2018-10-28T18:44:08+0000
            [from] => Array
                (
                    [name] => Usuario3
                    [id] => 33333333
                )

            [message] => ccccc
            [id] => 223423421243123412341234123
        )

    [3] => Array
        (
            [created_time] => 2018-10-28T18:43:44+0000
            [from] => Array
                (
                    [name] => Usuario2
                    [id] => 22222222
                )

            [message] => test other
            [id] => 23424123412341234
        )


)

请注意,数组中有ID项,对于此项,必须检查它是否重复,然后我必须从数组中删除记录。

3 个答案:

答案 0 :(得分:1)

在这里,请使用array_filter:

<?php
$comment = [
    [
        "created_time" => new DateTime(),
        "from" => [
            "name" => "test1",
            "id" => 1
        ],
        "message" => "test1",
        "id" => 4234234214123412341234124
    ],
    [
        "created_time" => new DateTime(),
        "from" => [
            "name" => "test2",
            "id" => 1
        ],
        "message" => "test2",
        "id" => 17481419471248
    ]
];
$temp = array();
$comment = array_filter($comment, function ($v) use (&$temp) {
    if (in_array($v['from']['id'], $temp)) {
        return false;
    } else {
        array_push($temp, $v['from']['id']);
        return true;
    }
});

var_dump($comment);

答案 1 :(得分:1)

这是使用apollo: {}array_reduce的功能解决方案,没有副作用。

array_filter替换为包含数据的变量,然后可以将$arr_in之后的代码替换为考虑记录重复所需的任何规则。

// Check if keys match

答案 2 :(得分:0)

只需索引一下:

foreach ($comments as $el) {
    $temp[$el['from']['id']] = $el;
}
$comments = array_values($temp);