0

I have a multidimesional array like this:

Array
(
[0] => Array
    (
        [ID] => 1
        [date_start] => 2016-07-30
        [customerID] => 15
        [job_type] => service
    )

[1] => Array
    (
        [ID] => 2
        [date_start] => 2016-08-10
        [customerID] => 12
        [job_type] => service
    )

[2] => Array
    (
        [ID] => 3
        [date_start] => 2016-08-20
        [customerID] => 15
        [job_type] => service
    )

etc

I would like to sort the data, so that it displays in "date_start" order, but keeping the customerID together.

So, in the above code, if I sort by date_start, it would put them in the order of:

ID - 1,2,3.

However, I want to keep the customer ID's together, but still sorting by date_start. Therefore, I want the order to be:

ID - 1,3,2

So, in essence, I need it to group the customers, find the earliest date for that customer, and sort by this earliest date.

Is this possible?

Thanks

8
  • 1
    Is this from a database? You could use ORDER BY Commented Jul 13, 2016 at 13:47
  • 2
    Possible duplicate of Sort multidimensional array by multiple keys Commented Jul 13, 2016 at 13:48
  • Yes, it's from a database, but ORDER BY doesn't allow me to order in this way, as far as I can see. This isn't just an "Order By date_start, customerID" call, as that will not keep the customers together. Commented Jul 13, 2016 at 15:17
  • I would flip that Order By customerID, date_start and from what I can tell it should. Commented Jul 13, 2016 at 15:33
  • That would result in the ID order of 2,1,3. I want to keep the customers together, not sort by them. Commented Jul 13, 2016 at 16:04

1 Answer 1

2

Use array_multisort :

function orderMultiArray(array $data)
    {
        $sort = array();

        foreach ($data as $key => $value) {
            $sort['date_start'][$key] = $value['date_start'];
            $sort['customerID'][$key] = $value['customerID'];
        }

        array_multisort($sort['date_start'], SORT_ASC, $sort['customerID'], SORT_ASC, $data);

        return $data;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Just tried that function, and running it keeps the order as, ID 1,2,3.

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.