将重复的数组值放入子数组中

时间:2014-01-05 14:26:55

标签: php arrays duplicates

我有一个从MYSQL查询创建的数组,它可能有重复的值,如下所示:

Array
(
    [0] => title1
    [1] => title2
    [2] => title2
    [3] => title3
    [4] => title4
    [5] => title5
    [6] => title6
    [7] => title6
    [8] => title6
)

我不想删除这些值,因此array_unique()在这里没有帮助。相反,我想将子数组中的重复值分组,以便新数组变为:

Array
(
    [0] => title1
    [dupe1] => Array
        (
            [0] => title2
            [1] => title2
        )

    [1] => title3
    [2] => title4
    [3] => title5
    [dupe2] => Array
        (
            [0] => title6
            [1] => title6
            [2] => title6
        )
)

编辑:我尝试了以下内容:

$clean = array_unique( $array );
$dupes = array_diff($array, array_diff($array, array_diff_assoc($array, $clean)));

foreach ($dupes as $k => $v)
{
    if (in_array($v, $clean))
    {
        $key = array_search($v, $clean);
        unset($clean[$key]);
    }

    $clean[$v]['dupe'][] = $v;
}


dumpArray(array_values($clean));

输出:

Array
(
    [0] => title1
    [1] => title3
    [2] => title4
    [3] => title5
    [4] => Array
        (
            [dupe] => Array
                (
                    [0] => title2
                    [1] => title2
                )

        )

    [5] => Array
        (
            [dupe] => Array
                (
                    [0] => title6
                    [1] => title6
                    [2] => title6
                )

        )

)

2 个答案:

答案 0 :(得分:0)

所以这是一种你可以做到的方法。创建一个HashMap,标题作为键,原始数组中的索引作为值。这将为您提供组合在一起的副本。

答案 1 :(得分:0)

由于您希望保留(原始)订单,您可以使用array_splice和类似于当前的方法工作,也可以完全构建$clean新方法 - 如下所示(请参阅here):

sort($array);
$unique_length = count( array_unique($array) );
$total_dupes = 0;

$clean = array();

for ($i=0; $i<$unique_length; $i++) {
    $current = array_shift($array);
    if ($current === NULL)//already have all elements
        break;

    $found = 1;
    while (($key = array_search($current, $array)) !== FALSE) {//search for dupes
        $found++;
        unset($array[$key]);
    }

    if ($found == 1)
        array_push($clean, $current);
    else {
        $dupes = array();
        for ($i=0; $i<$found; $i++)
            $dupes[] = $current;
        $total_dupes++;
        $clean['dupe'.$total_dupes] = $dupes;
    }
}