-1

I've this array:

[0] => Array
    (
        [0] => 0
        [1] => 1
    )

[1] => Array
    (
        [0] => 3
        [1] => 4
    )

[2] => Array
    (
        [0] => 2
    )

I need to sort the values to obtain an array, sorted by single array values, like:

[0] => Array
    (
        [0] => 0
        [1] => 1
    )

[2] => Array
    (
        [0] => 2
    )

[1] => Array
    (
        [0] => 3
        [1] => 4
    )

The values (0,1,2,3,4) are unique and represents the days of the week, so, I can have maximum 7 unique values.

I've tried with usort but unsuccessfully. Any ideas? Thanks a lot

Stefano P.
  • 9
  • 1
  • 4
  • 3
    1) Show your attempt 2) How is this sorted? (How would you array looks like if the input is: `[[1, 100], [-1, 50], [75]]`?) – Rizier123 May 14 '16 at 20:49
  • Hi Rizier, the values (0,1,2,3,4) are unique and represents the days of the week, so, I can have maximum 7 unique values... My attempts aren't presentables... – Stefano P. May 14 '16 at 21:04

1 Answers1

2

This depends on how you want to sort your arrays. In your example, you sort the second level arrays low to high, then sort the first level array by the lowest value in the second level array, so I'm going to assume that's what you'd like.

You could do this sort of thing with usort, but I find just using asort() and a bit more code helps readability.

//Setup variables
$start_array = array( array(0,1), array(3,4), array(2));
$lowest_value = array();
$sorted_array = array();

//Sort your inner arrays and build up a list of lowest values
foreach($start_array as $key => $inner_array) {
    sort($start_array[$key]);
    $lowest_value[$key] = $start_array[$key][0];
}

//Iterate over your lowest values and map to your new array
asort($lowest_value);
foreach($lowest_value as $key => $value){
    $sorted_array[] = $start_array[$key];
}

Note that this assumed you wanted your first level array sorted by the second levels lowest values. You can alter this with the line $lowest_value[$key] = $start_array[$key][0]; by instead grabbing the average of the inner array, highest value, whatever you'd like.