1

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

IE

Array (10, 2, 5, 1, 30, 1, 7)

应该 :

(30, 1, 10, 1, 7, 2, 5)

编辑:

忘了提到数组是关联的,所以:

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

应该变成:

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

4 回答 4

1

对数组进行排序,然后交替从数组的开头和结尾推送元素:

<?php

    $myArray = array(10, 2, 5, 1, 30, 1, 7);
    sort($myArray );
    $count=sizeof($myArray );

    $result= array();
    
    for($counter=0; $counter * 2 < $count; $counter++){

         array_push($result, $myArray[$count - $counter - 1]);
         //check if same elements (when the count is odd)
         if ($counter != $count - $counter - 1) {
             array_push($result, $myArray[$counter]);
         }

    }
    print_r ($result);

?>

返回:

Array ( [0] => 30 [1] => 1 [2] => 10 [3] => 1 [4] => 7 [5] => 2 [6] => 5 )
于 2012-11-29T10:37:23.057 回答
0

我不能告诉你确切的语法,我的 php 很生锈,但你可以做什么:

  • 按降序对数组进行排序

  • 分成两半,比如说数组 A 和 B;

  • 创建一个新数组并按顺序添加 A 和 B 中的每个元素$A[i], $B[count($B)-1-i]

这应该给你你需要的

于 2012-11-29T10:39:20.737 回答
0

没有预定义的方法可以做到这一点。但是,php 允许用户排序​​功能usort ,您可以自定义该功能以按照您需要的方式对数组进行排序。

于 2012-11-29T10:35:16.900 回答
0
<?php
$x = array(10, 2, 5, 1, 30, 1, 7);

// First sort
sort($x);

// Then pick highest and lowest from the back and front of the array
// until it is empty.
$z = array();
while (count($x) > 0){
    $z[] = array_pop($x);
    if (count($x) > 0) // <- For arrays with an odd number of elements.
      $z[] = array_shift($x);
}

var_dump($z);
于 2012-11-29T10:43:22.957 回答