PHP特定类型的数字

时间:2013-02-10 18:39:39

标签: php arrays sorting numbers

我有以下类型的数组:

$foo = array(
         "a" => 1,
         "b" => 1,
         "c" => 2,
         "d" => 2,
         "e" => 3,
         "f" => 3,
         "g" => 4,
         "h" => 4,
         "i" => 5,
         "j" => 5,
         "k" => 10,
         "l" => 12,
         "m" => 15,
         "n" => 20
       );

我需要以这种方式对数组进行排序:

$foo = array(1,2,3,4,5,12,20,15,10,5,4,3,2,1);

如您所见,最佳值需要位于数组的中间。并且数组的开始/结束中的最小值。密钥需要与原始值相关联。

感谢您的帮助!对不起我的英文。

2 个答案:

答案 0 :(得分:4)

如果输入已经排序,你可以使用两个循环首先按升序排列奇数偏移的每个项目,然后按顺序将偶数偏移的每个项目按到你的数组中:

$keys = array_keys($foo);
$n = count($keys);
$result = array();
for ($i=0; $i<$n; $i+=2) {
    $result[$keys[$i]] = $foo[$keys[$i]];
}
for ($i=$n-$n%2-1; $i>0; $i-=2) {
    $result[$keys[$i]] = $foo[$keys[$i]];
}

答案 1 :(得分:0)

一个矫枉过正的版本:

<?php
$foo = array(
        "a" => 1,
        "b" => 1,
        "c" => 2,
        "d" => 2,
        "e" => 3,
        "f" => 3,
        "g" => 4,
        "h" => 4,
        "i" => 5,
        "j" => 5,
        "k" => 10,
        "l" => 12,
        "m" => 15,
        "n" => 20
);

$arrayKeys = array_keys($foo);
$arrayValues = array_values($foo);

$array_count = count($foo);
for ($idx =0; $idx < round($array_count/2); $idx+=2) {
    $tmpA = $arrayKeys[$idx];
    $arrayKeys[$idx] = $arrayKeys[$array_count - $idx -1];
    $arrayKeys[$array_count - $idx -1] = $tmpA;

    $tmpB = $arrayValues[$idx];
    $arrayValues[$idx] = $arrayValues[$array_count - $idx -1];
    $arrayValues[$array_count - $idx -1] = $tmpB;
}

$tmpArray = array_combine($arrayKeys, $arrayValues);

$ascent = array_slice($tmpArray, 0, round($array_count/2));
$descent = array_slice($tmpArray, round($array_count/2));

asort($ascent);
arsort($descent);

$foobar = array_merge($ascent, $descent);

var_dump($foo, $foobar);
?>