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

oprakyz7  于 2023-04-10  发布在  PHP
关注(0)|答案(5)|浏览(147)

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

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)
bvuwiixz

bvuwiixz1#

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

<?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 )
ugmeyewa

ugmeyewa2#

<?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);
yws3nbqq

yws3nbqq3#

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

  • 按降序对数组排序
  • 将数组A和B分成两半;
  • 创建一个新数组,并将A和B中的每个元素按顺序$A[i], $B[count($B)-1-i]相加

这应该能给予你的需要

3z6pesqy

3z6pesqy4#

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

42fyovps

42fyovps5#

$arr = [2,10,11,12,4,18];

$final_arr = [];
$max = $min = '';
for($i =0 ;$i <=count($arr);$i++){
    $max = max($arr);
    $final_arr[] = $max;
    $index = array_search($max, $arr);
    unset($arr[$index]);
    $min = min($arr);
    $final_arr[] = $min;
    $index = array_search($min, $arr);
    unset($arr[$index]);
}
print_r($final_arr);

相关问题