sort array values by key using php

i have an PHP array in the following format,

Array
(
    [0] => Array
        (
            [40] => 2
            [80] => 1
            [20] => 0
            [60] => 0
            [100] => 0
        )

    [1] => Array
        (
            [60] => 2
            [80] => 1
            [20] => 0
            [40] => 0
            [100] => 0
        )
)

Expected output is (20=>0,40=>0,60=>2,80=>1 etc)
i tried using array_values and array_combine, but no luck.

How do i sort array by key using PHP.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use array_combine (http://php.net/manual/en/function.array-combine.php) to combine the arrays and then use ksort (http://php.net/manual/en/function.ksort.php) to sort the keys.

Solution 2

use ksort , which sorts an array by key

Assuming your array is $array

foreach($array as $a){
   foreach($a as $sort_me){
     ksort($sort_me);
   }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply