PHP-打印数组的偶数和(排序的)奇数 [英] php - print even and (sorted) odd numbers of an array

查看:77
本文介绍了PHP-打印数组的偶数和(排序的)奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面给出了一个数组

I have an array given below

$array = array(50,51,52,53,54,55,56,57,58,59);

我正在尝试打印数组的值,而偶数将保持相同的顺序,而奇数将被排序,即59,57,55,53,51

I am trying to print the values of array while even numbers will remain in same order and the odd numbers are sorted i.e. 59,57,55,53,51

输出应类似于

50,59,52,57,54,55,56,53,58,51

我已经在两个diff变量中分离了偶数和奇数.我应该怎么做?

I've separated the even and odd numbers in two diff variables. how should i proceed further ?

这是我的代码

  $even= "";
  $odd= "";

for($i=50;$i<=59;$i++)
{
    if($i%2==0)
    {
        $even.=$i.",";
    }else $odd.=$i.","; 
}   
echo $even.$odd; 

推荐答案

不是将偶数和几率压入一个字符串,而是将它们分别压入一个数组,对这些具有相反几率的数组进行反向排序,然后循环遍历其中的一个(最好通过偶数数组),并将偶数和奇数添加到新数组中.

Instead of pushing the evens and odds into a string, push them each into an array, sort the array with the odds in reverse and then loop through one of them (preferably through the even array) and add the even and the odd to a new array.

这是我的操作方式:

$array = array(50,51,52,53,54,55,56,57,58,59);
$odds = array();
$even = array();
foreach($array as $val) {
    if($val % 2 == 0) {
        $even[] = $val;
    } else {
        $odds[] = $val;
    }
}

sort($even);
rsort($odds);

$array = array();
foreach($even as $key => $val) {
    $array[] = $val;
    if(isset($odds[$key])) {
        $array[] = $odds[$key];
    }
}

https://3v4l.org/2hW6T

但是,如果您的奇数个数小于偶数,则应保持谨慎,因为循环将在所有奇数加在一起之前完成.您可以在填充新数组之前或之后进行检查.如果在填充新数组后进行检查,则可以使用 array_diff array_merge 将丢失的赔率添加到新数组中.

But you should be cautious if you have less even than odd numbers, as the loop will finish before all odds are added. You can check for that either before or after you've filled the new array. If you check after filling the new array, you can use array_diff and array_merge to add the missing odds to the new array.

http://php.net/array_diff 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆