Search code examples
phpsortingmultidimensional-arraykey

Sort 1st and 3rd level of a multidimensional array by keys


I have this multidimensional array, called $rent:

Array
(
    [product2] => Array
        (
            [dates] => Array
                (
                    [2013-07-25] => 2
                    [2013-07-23] => 1
                    [2013-07-21] => 3
                )

        )

    [product3] => Array
        (
            [dates] => Array
                (
                    [2013-07-24] => 5
                    [2013-07-22] => 4
                    [2013-07-20] => 3
                )

        )

    [product1] => Array
        (
            [dates] => Array
                (
                    [2013-07-29] => 1
                    [2013-07-28] => 2
                    [2013-07-27] => 2
                )

        )

)

I'd like to do a double sort:

  1. First, by productX ascending
  2. Then, for each product, by date of rent ascending

So that the resulting array would be:

Array
(
    [product1] => Array
        (
            [dates] => Array
                (
                    [2013-07-27] => 2
                    [2013-07-28] => 2
                    [2013-07-29] => 1
                )

        )

    [product2] => Array
        (
            [dates] => Array
                (
                    [2013-07-21] => 3
                    [2013-07-23] => 1
                    [2013-07-25] => 2
                )

        )

    [product3] => Array
        (
            [dates] => Array
                (
                    [2013-07-20] => 3
                    [2013-07-22] => 4
                    [2013-07-24] => 5
                )

        )

)

How can I reach this? Many thanks in advance


Solution

  • try this:

    ksort($rent);
    foreach($rent as &$item) {
        ksort($item['dates']);
    }