问题描述
的阵列到达与一些或全部的下列值中的,以任何顺序。什么是责令其按升序大小顺序的最好方法?所以,开始小规模的和XXL结束。我可以usort但我有点失落至于如何要素应该在我的用户自定义函数进行排序。
An array arrives with some or all of the following values, in any order. What's the best way to order them in ascending size order? So starting with small and ending with XXL. I can usort but am a bit lost as to how the elements should be ordered in my user defined function
Small
XXL
Medium
Large
XL
编辑:留下了一些信息,以便创建新问题http://stackoverflow.com/questions/4014743/custom-ordering-array-with-key-value-pairs
EDIT2:全code
Full code
print_r($sizes);
$sorted_sizes = $this->sort_sizes(array_unique($sizes));
print_r($sorted_sizes);
function sort_sizes($sizes)
{
return uasort($sizes, array($this, 'cmp'));
}
function cmp($a,$b)
{
$sizeArray = array( 'Small' => 0, 'Medium' => 1, 'Large' => 2, 'XL' => 3, 'XXL' => 4);
return $sizeArray[$a] - $sizeArray[$b];
}
此输出:
Array
(
[66-507cddcd16d9786abafccfa78b19acf8] => XL
[64-507cddcd16d9786abafccfa78b19acf8] => medium
[65-507cddcd16d9786abafccfa78b19acf8] => large
[63-507cddcd16d9786abafccfa78b19acf8] => small
)
和的print_r($ sorted_sizes)只是给输出1
and print_r($sorted_sizes) just gives output "1"
推荐答案
根据全code更新的答案
这里的第一个问题是,你回来 uasort()
的结果是:
The first issue here is that you're returning the result of uasort()
:
function sort_sizes($sizes)
{
return uasort($sizes, array($this, 'cmp'));
}
这是错误的,因为 uasort()
不返回排序的数组。它会修改你作为参数传递相同的变量,并返回一个布尔值。这就是为什么你看到 1
作为输出。
That's wrong, because uasort()
does not return the sorted array. It modifies the same variable that you pass as a parameter, and returns a boolean value. That's why you see 1
as output.
请方法接受 $大小
引用:
function sort_sizes(array &$sizes)
{
uasort($sizes, array($this, 'cmp'));
}
然后调用它像这样:
Then call it like so:
print_r($sizes);
$sorted_sizes = array_unique($sizes);
$this->sort_sizes($sorted_sizes);
print_r($sorted_sizes);
这是你的 CMP()
方法,为不区分大小写的排序额外支持:
Here's your cmp()
method, with added support for case-insensitive sorting:
function cmp($a, $b)
{
$sizes = array('small' => 0, 'medium' => 1, 'large' => 2, 'xl' => 3, 'xxl' => 4);
return $sizes[strtolower($a)] - $sizes[strtolower($b)];
}
旧的答案
试试这个。使用 uasort()
来代替,如果你想maintain键 - 值对的:
Try this. Use uasort()
instead if you want to maintain key-value pairs:
function sort_sizes($a, $b) {
// Map the sizes to an ordered sequence of ints
static $sizes = array('small' => 0, 'medium' => 1, 'large' => 2, 'xl' => 3, 'xxl' => 4);
// Find the difference, using the sizes as keys to the above array
return $sizes[strtolower($a)] - $sizes[strtolower($b)];
}
$arr = array('Small', 'XXL', 'Medium', 'Large', 'XL');
print_r($arr); // Before sorting
uasort($arr, 'sort_sizes');
print_r($arr); // After sorting
输出:
Array
(
[0] => Small
[1] => XXL
[2] => Medium
[3] => Large
[4] => XL
)
Array
(
[0] => Small
[2] => Medium
[3] => Large
[4] => XL
[1] => XXL
)
这篇关于PHP的自定义排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!