ksort似乎没有用

时间:2015-03-23 14:54:40

标签: php ksort

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

ksort($listings, SORT_NUMERIC);

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

输出:

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
        )

)

我尝试了foreach,但它不会影响原始数组,for将无效,因为它是一个键,而不是索引。在这种情况下我该怎么做?

2 个答案:

答案 0 :(得分:4)

您在此$listings数组中嵌套了数组。要对它进行排序,请按以下方式编写:

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

答案 1 :(得分:1)

array_walk(
    $listings,
    function(&$value) {
        ksort($value, SORT_NUMERIC);
    }
);