0

我正在查看 PHP 数组排序函数以找到一些方法来执行以下操作,但似乎无法管理它。

例子

Array ( 
[77] => 79
[72] => 78
[71] => 78
[82] => 79
[76] => 79
[73] => 78
[75] => 78 )

我想重新订购

Array ( 
[72] => 78
[71] => 78
[73] => 78
[75] => 78
[77] => 79
[82] => 79
[76] => 79 )

请注意键对它们最初所在顺序的尊重方式,它们只是根据值排列(因此 79 中的第一个 77 仍然是 79 中的第一个等)

我以为 aasort 会工作,但它没有

asort($categories);
foreach ($categories as $key => $val) {
    echo "$key = $val\n";
    echo "<br>";
}

输出(请原谅等号)

74 = 78
85 = 78
75 = 78
73 = 78
70 = 78
71 = 78
72 = 78
82 = 79
86 = 79
81 = 79
77 = 79
80 = 79
76 = 79 
4

4 回答 4

3

正如 Mark 建议的那样,可能将其集成到冒泡排序的某些实现中,但会在速度上进行权衡。如果一开始速度不是问题,那么这里有一个简单的实现,可以满足您的需求。

它只计算用于特定值的键,然后确保最终排序的数组遵守该顺序:

function sort_keys_intact(&$a) {
    $b = array();
    $values = array();
    foreach ( $a as $k => $v ) {
        $values[$v][] = $k;
    }
    asort($a);
    $used = 0;
    foreach ( $a as $k => $v ) {
        if ( $used == count($values[$v]) + 1 ) {
            $used = 0;
        }
        $b[$values[$v][$used]] = $v;
        $used++;
    }
    $a = $b;
}

试运行

echo 'Before:' . PHP_EOL;
print_r($categories);
sort_keys_intact($categories);
echo 'After:' . PHP_EOL;
print_r($categories);

输出

Before:
Array
(
    [77] => 79
    [72] => 78
    [71] => 78
    [82] => 79
    [76] => 79
    [73] => 78
    [75] => 78
)
After:
Array
(
    [72] => 78
    [71] => 78
    [73] => 78
    [75] => 78
    [77] => 79
    [82] => 79
    [76] => 79
)
于 2013-08-09T18:33:49.667 回答
0

Not familiar with PHP so not sure how you'd do it in PHP (perhaps thats the problem) but you could create a second list that looks like this:

[77] => (79,1)
[72] => (78,2)
[71] => (78,3)
[82] => (79,4)
[76] => (79,5)
[73] => (78,6)
[75] => (78,7)

This is a tuple with the original value and the order value. Do a sort, then remove the ordering for each, to produce the desired format.

于 2013-08-09T18:10:08.707 回答
0

我会做这样的事情:

function my_sort(&$array)
{
  $i = 0;
  foreach ($array as &$val)
    $val = [$i++, $val];

  uasort($array, function($a, $b) {
    return $a[1] - $b[1] ?: $a[0] - $b[0];
  });

  foreach ($array as &$val)
    $val = $val[1];
}

我认为这只是@Nuclearman 答案的实现。

这假设所有值都是整数。如果不是这种情况,您必须更改$a[1] - $b[1]以反映值的排序方式。(如果值相同,则排序函数返回$a[0] - $b[0]。)

于 2013-08-09T18:58:41.470 回答
0

答案对我没有用,所以我写了一个函数来解决这个问题:

function sort_value_leave_key(&$arr){

$z = array();
foreach ($arr as $k => $v){
    $z[$v.rand(1111,9999)] = $k;
}
krsort($z);

$arr = array();
foreach($z as $k => $v){
    $arr[$v] = substr($k,0,-4);
}

}
于 2014-03-19T23:55:35.670 回答