2

What is the best method to preserve the order of an array while placing duplicate values in order.

Here is the array:

Array
(
    [0] => Array
        (
            [location] => 1320 N Street
        )

    [1] => Array
        (
            [location] => 1316 N St

        )

    [2] => Array
        (
            [location] => 1320 N Street
        )

)

I would like to group duplicate locations so it looks like this:

    Array
(
    [0] => Array
        (
            [location] => 1320 N Street
        )

    [1] => Array
        (
            [location] => 1320 N Street

        )

    [2] => Array
        (
            [location] => 1316 N St
        )

)

My initial thought was to loop through the array and perform an array_search on the location key to get the index a duplicate location, then perform a shift to move the location.

Thanks for your time.

2
  • Yep, I'd do a loop through the array and put each element into a new array and search for any duplicates in the existing array and cut them out of the original (so that they won't get looped through) and put them into the new. Commented Apr 27, 2012 at 1:45
  • There's many different sorting option functions for arrays in PHP. Look here: http://php.net/manual/en/array.sorting.php Commented Apr 27, 2012 at 1:47

2 Answers 2

1

This worked for me:

$arr = array(
        array("location" => "1320 N Street"),
        array("location" => "1320 N St"),
        array("location" => "1320 N Street"),
);

$tmp = array();
$sorted = array();
foreach ($arr as $k => $v)
{
        $s = serialize($v);
        if (!isset($tmp[$s]))
        {
                $tmp[$s] = $k;
                array_push($sorted, $v);
        } else {
                $sorted = array_merge(array_slice($sorted, 0, $tmp[$s]+1), array($v), array_slice($sorted, $tmp[$s]+1));
        }
}

print_r($sorted);

Sample Output:

Array
(
    [0] => Array
        (
            [location] => 1320 N Street
        )

    [1] => Array
        (
            [location] => 1320 N Street
        )

    [2] => Array
        (
            [location] => 1320 N St
        )

)

Edit: Instead of $s = serialize($v); you could also use any key you like, for example $s = $v["location"]; if it's just the location that matters.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use array_multisort() to do this.

array_multisort($sub_array[0], SORT_ASC, SORT_STRING,
                $sub_array[1], SORT_NUMERIC, SORT_DESC);

1 Comment

array_multisort wouldn't necessarily preserve the order of non-duplicates, which is that he wants I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.