0

有谁知道如何将关联数组排序为交替的最大最小值?

IE

array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7)

应该变成:

array("E"=>30, "D"=>1, "A"=>10, "F"=>1, "G"=>7, "B"=>2, "C"=>5)

谢谢

4

1 回答 1

2

根据您对此问题的先前版本的回答:

$myArray = array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7);
asort($myArray);
$myArrayKeys = array_keys($myArray);

$newArray = array();
while (!empty($myArray)) {
    $newArray[array_shift($myArrayKeys)] = array_shift($myArray);
    if (!empty($myArray))
        $newArray[array_pop($myArrayKeys)] = array_pop($myArray);
}
var_dump($newArray);

或者,如果你想要最大的第一:

$myArray = array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7);
asort($myArray);
$myArrayKeys = array_keys($myArray);

$newArray = array();
while (!empty($myArray)) {
    $newArray[array_pop($myArrayKeys)] = array_pop($myArray);
    if (!empty($myArray))
        $newArray[array_shift($myArrayKeys)] = array_shift($myArray);
}
var_dump($newArray);
于 2012-11-29T11:42:29.643 回答