user3296337 user3296337 - 6 months ago 11
PHP Question

Sorting PHP array with duplicates

Using PHP I have this array:

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


I want to sort the array so that the order is as close to the original as possible, but with duplicates stacked, creating the following array:

[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


I'm assuming that it's a matter of nested foreach loops, but I'm unsure how to apply unset() in a nested foreach loop.

EDIT: Since i probably didn't explain it very well I want to keep the duplicates in the array. I do not want to remove the duplicates.

Answer

Not the most efficient solution, but works:

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;
}