Search code examples
phpksort

ksort doesn't seem to work


echo '<pre>'.print_r($listings,1).'</pre>';

ksort($listings, SORT_NUMERIC);

echo '<pre>'.print_r($listings,1).'</pre>';

Output:

Array
(
    [quick-brown-fox] => Array
        (
            [0] => Quick-brown-fox
            [1] => quick-brown-fox
            [4] => general_thumbs/quick-brown-fox.jpg
            [2] => 320
            [3] => 240
        )

)

Array
(
    [quick-brown-fox] => Array
        (
            [0] => Quick-brown-fox
            [1] => quick-brown-fox
            [4] => general_thumbs/quick-brown-fox.jpg
            [2] => 320
            [3] => 240
        )

)

I tried foreach, but it won't affect the original array, and for won't work because the its a key, not an index. What should I do in that case?


Solution

  • You have nested array in this $listings array. To sort it, write it like this:

    foreach($listings as $k => $a){
        ksort($a, SORT_NUMERIC);
        $listings[$k] = $a;
    }