使用usort和strcomp重新排序PHP数组:bug

使用usort和strcomp重新排序PHP数组:bug

问题描述:

Using usort and strcomp together to order an array by one of its keys has an odd effect: it returns my array with fewer items in it than I put in.

The array in my case contains rows representing tasks, and I want to order the rows in the array by the key 'displayorder', which is a number but which I want to be sorted in alphabetical manner (don't ask why).

function treeSort($a, $b) {
        return strcmp(strval($a['displayOrder']), strval($b['displayOrder']));
    }

usort($tree, "treeSort");

There are nine rows, but I only get six of them back. Those six are nicely sorted, by the way. If I use uasort instead of usort, I do get all nine rows, but ordered in a numerical way.

使用usort和strcomp一起按其中一个键对数组进行排序有一个奇怪的效果:它返回我的数组 它中的项目比我输入的项目少。 p>

我的案例中的数组包含代表任务的行,我想通过键'displayorder'来排序数组中的行,这是一个 数字,但我想按字母方式排序(不要问为什么)。 p>

  function treeSort($ a,$ b){
 return strcmp(strval(  $ a ['displayOrder']),strval($ b ['displayOrder'])); 
} 
 
usort($ tree,“treeSort”); 
  code>  pre> 
 \  n 

有九排,但我只有六排。 顺便说一句,这六个很好地排序。 如果我使用uasort而不是usort,我会得到所有九行,但是以数字方式排序。 p> div>

I've found a solution: array_multisort. That's probably what you'd have proposed Tim if I had given you the details on $tree.

Got the code from the examples in the documentation on array_multisort:

foreach ($tree as $key => $row) {
        $sortOrder[$key] = $row['displayOrder'];
    }
    array_multisort($sortOrder, SORT_STRING, $tree);