[Solved] In PHP, how to sort associative array sorting based on key [closed]


ksort is PHP’s function to sort by key. So to sort an array $arr by its keys, do:

ksort($arr);

Note that ksort returns a boolean (success or failure), so you shouldn’t do $arr = ksort($arr);. ksort modifies the original array.

To sort a multidimensional associative array (say, an associative array of associative arrays) recursively by keys, try the user-provided function at the bottom of the ksort manual page (I haven’t tried this, but it looks like it will work just fine):

function deep_ksort(&$arr) {
    ksort($arr);
    foreach ($arr as &$a) {
        if (is_array($a) && !empty($a)) {
            deep_ksort($a);
        }
    }
}

2

solved In PHP, how to sort associative array sorting based on key [closed]