0

I have this array:

Array ( 
[order] => Array ( [0] => 2 [1] => 1 )
[eventid] => Array ( [0] => id_1 [1] => id_2 )
 ) 

Now I would like to get:

Array ( 
[order] => Array ( [0] => 1 [1] => 2 )
[eventid] => Array ( [0] => id_2 [1] => id_1 )
)

Basically I would like to sort arrays by value of order.

El Danielo
  • 780
  • 1
  • 8
  • 18

2 Answers2

4

You will need to use the usort function to be able to do this. (See the documentation)

I would recommend another Array structure though, something like this:

Array ( 
[0] => Array ( [order] => 2, [eventid] => id_x )
[1] => Array ( [order] => 1, [eventid] => id_y )
)

Then you could a function like this one to sort your array (PHP 5.3 or greater):

function array_sort_by(&$array, $key, $descending = false) {
    $sortByKey =
        function ($a, $b) use ($key, $descending) {
            if ($a[$key] === $b[$key]) {
                return 0;
            }
            $return = $a[$key] < $b[$key] ? -1 : 1;
            return ($descending ? -1 * $return : $return);
        };

    usort($array, $sortByKey);
}

You would then call the following:

array_sort_by($yourArray, 'order');
Ken Foncé
  • 56
  • 4
  • Love you! I had to change some of attributes in html form to change the array layout but now it works! Thank you! – El Danielo Dec 08 '15 at 17:22
0

You can use asort. While it can cover your case, usort might be a better solution in the long run.

$arr = Array ( 
     "order" => Array ( 0 => 6, 1 => 1,2=>43),
     "eventid" => Array ( 0 => 5, 1 => 1,2=>54,3=>0)
 ); 

foreach ($arr as $key => &$value) {
 asort($value);
}
Tito
  • 44
  • 4