将数组排序为交替最小的最大值?

时间:2012-11-29 10:30:23

标签: php arrays

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

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 个答案:

答案 0 :(得分: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 )

答案 1 :(得分:0)

没有预定义的方法来执行此操作。但是,php允许用户排序​​函数usort,您可以自定义该函数以按照您需要的方式对数组进行排序。

答案 2 :(得分:0)

我无法告诉你确切的语法,我的php非常生疏,但你能做什么:

  • 按降序对数组进行排序

  • 分成两半,比如阵列A和B;

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

这应该可以满足您的需求

答案 3 :(得分: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);
相关问题