PHP - 如何在数组中找到重复项,删除但添加到下一个数组

时间:2017-07-16 18:46:57

标签: php arrays duplicates

我正在使用php。我有一个多维数组,时间排序,从其他数组创建array_merge(),从多个MySql数据库创建。目的是创建活动日志。这一切都有效,但我有多个条目说;

X uploaded image a
X uploaded image b
这是非常正确但浪费空间。

Array
(
    [3] => Array
        (
            [time] => 1500218082
            [user] => James
            [desc] => James posted to forum a_hippo
        )
    [0] => Array
        (
            [time] => 1499294355
            [user] => Tom
            [desc] => Tom edited a wiki page a_tree
        )
    [1] => Array
        (
            [time] => 1498939657
            [user] => Bob
            [desc] => Bob uploaded image a_badger
        )
    [2] => Array
        (
            [time] => 1498939656
            [user] => Bob
            [desc] => Bob uploaded image a_rabbit
        )
)

我想要做的是卷起键[1]和[2]所以[desc]说bob上传的图像a_badger&一只兔子。我的研究发现了" array_unique"但我不想完全删除。和How to detect duplicate values in PHP array?

有人可以帮忙吗? 谢谢 克里斯

2 个答案:

答案 0 :(得分:0)

只需使用缓冲区来存储新数组。

$result = array();

// $data is your array
foreach ($data as $row) {
    if (isset($result[$row->user])) {
       $result[$row->user] .= ' and '. trim(str_replace($row->user, '', $row->desc));
    } else {
       $result[$row->user] = $row->desc;
    }
}

// then loop through result var
// each row is a sentence 

答案 1 :(得分:0)

这可能有所帮助:

$dup = [];
$array =
[
    "3" => 
    [
        "time" => "1500218082",
        "user" => "James",
        "desc" => "James posted to forum a_hippo"
    ],
    "0" => 
    [
        "time" => "1499294355",
        "user" => "Tom",
        "desc" => "Tom edited a wiki page a_tree"
    ],
    "1" =>
    [
        "time" => "1498939657",
        "user" => "Bob",
        "desc" => "Bob uploaded image a_badger"
    ],
    "2" =>
    [
        "time" => "1498939656",
        "user" => "Bob",
        "desc" => "Bob uploaded image a_rabbit"
    ]
];

//you could use this with modification of the index
foreach($array as $r)
{
    if(!empty($dup[$r['user']]))
    {
        $descArr = explode($r['user'], $r['desc']);
        $dup[$r['user']]['desc'] .= ' & '. trim(end($descArr));
    }
    else
    {
        $dup[$r['user']] = $r;
    }
}

print_r($dup);

编辑:这支持任何desc不仅仅是图片上传。