使用重复项对PHP数组进行排序

时间:2016-05-24 20:00:06

标签: php arrays sorting

使用PHP我有这个数组:

[0]: John
[1]: Brian
[2]: Julia
[3]: Adam
[4]: Brian
[5]: Jonathan
[6]: Amanda
[7]: Julia
[8]: Nathan

我想对数组进行排序,使订单尽可能接近原始数据,但堆叠重复数据后,创建以下数组:

[0]: John
[1]: Brian
[2]: Brian (duplicate value moved from index 4)
[3]: Julia
[4]: Julia (duplicate value moved from index 7)
[5]: Adam
[6]: Jonathan
[7]: Amanda
[8]: Nathan

我假设这是嵌套的foreach循环问题,但我不确定如何在嵌套的foreach循环中应用unset()。

编辑:因为我可能没有很好地解释它,我想保留数组中的重复项。我不想删除重复项。

5 个答案:

答案 0 :(得分:1)

不是最有效的解决方案,但有效:

function dupsort(array $input)
{
    $output = array();
    $moved = array();
    foreach ($input as $key => $val)
    {
        if (isset($moved[$key])) {
            continue;
        }

        $moved[$key] = true;
        $output[] = $val;

        foreach ($input as $dupKey => $dupVal) {

            if ($dupVal!==$val) {
                continue;
            }

            if (isset($moved[$dupKey])) {
                continue;
            }

            $moved[$dupKey] = true;
            $output[] = $dupVal;
        }
    }

    return $output;
}

答案 1 :(得分:1)

使用array_shiftarray_intersectin_array函数的解决方案:

$arr = [0=> 'John',1=> 'Brian',2=> 'Julia',3=> 'Adam',4=> 'Brian',5=> 'Jonathan',6=> 'Amanda',7=> 'Julia',8=> 'Nathan'];

$size = count($arr);
$i = 0;
$result = [];
while ($i < $size) {
    $el = array_shift($arr);  // current value
    if (!in_array($el, $result)) $result[] = $el;
    $dups = array_intersect($arr, [end($result)]);  // finding duplicates
    if (count($dups)) $result = $result + $dups;    // adding duplicates to "stack" if exist
    $i++;
}

print_r($result);

输出:

Array
(
    [0] => John
    [1] => Brian
    [2] => Brian
    [3] => Julia
    [4] => Julia
    [5] => Adam
    [6] => Jonathan
    [7] => Amanda
    [8] => Nathan
)

答案 2 :(得分:0)

只需使用the sort function

$a = array("a", "b", "c", "a");

sort($a);
var_dump($a);

结果是:

array(4) { [0]=> string(1) "a" [1]=> string(1) "a" [2]=> string(1) "b" [3]=> string(1) "c" }

答案 3 :(得分:0)

它有效,只是经过测试。

POST /api/team -> insert team data

答案 4 :(得分:0)

请允许我提供更加资源友好的解决方案:

  function dupsort($data) {
    $result = [];

    foreach($data as $word) {

        // remove all matches of the current word from the source
        $before = count($data);
        $data = array_filter($data, function($x) use ($word) {
            return $x !== $word;
        });

        // add the word to the output as many times as it got removed from source
        $newCount = count($result) + $before - count($data);
        $result = array_pad($result, $newCount, $word);
    }

    return $result;
  }