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

P Diddly
  • 11
  • 4
  • 1
    Is this from a database? You could use `ORDER BY` – nerdlyist Jul 13 '16 at 13:47
  • 2
    Possible duplicate of [Sort multidimensional array by multiple keys](http://stackoverflow.com/questions/3232965/sort-multidimensional-array-by-multiple-keys) – nerdlyist Jul 13 '16 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. – P Diddly Jul 13 '16 at 15:17
  • I would flip that `Order By customerID, date_start` and from what I can tell it should. – nerdlyist Jul 13 '16 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. – P Diddly Jul 13 '16 at 16:04
  • Okay so use a desc... `Order By customerID DESC, date_start` – nerdlyist Jul 13 '16 at 16:17
  • No, that won't do it. I do not need the customerID sorted. The customerID number is only relevant in that I want them grouped together. I need the data sorted by date_start. If a particular customerID happens to have 20 entries, but one of them has a date_start that is the most current, then I want that particular to show first, followed by all other 19 entries for that customer. THEN, I want it to show the record that is next on the sorted list by date_start. – P Diddly Jul 13 '16 at 16:38
  • But you do... you can not want a list in order by something and then say that cannot set the order. – nerdlyist Jul 13 '16 at 16:59

1 Answers1

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;
    }
Poiz
  • 7,611
  • 2
  • 15
  • 17
rokas
  • 1,521
  • 9
  • 16