PHP - 如何数组的空值移动到它的最后位置 [英] PHP - How to move the empty values of an array to its last positions

查看:110
本文介绍了PHP - 如何数组的空值移动到它的最后位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以移动一个数组的空值的最后一个位置?

How can I move the empty values of an array to its last position?

例如:

$givenArray = array( 
                    0=>'green', 
                    1=>'', 
                    2=>'red', 
                    3=>'', 
                    4=>'blue'
                  );

$requiredArray = array(
                       0=>'green',
                       1=>'red',
                       2=>'blue',
                       3=>'',
                       4=>'' 
                      );

但非空值不应进行排序。它应该是因为它是,即,仅在空值应该移动到数组的末尾。

Provided that the non empty values should not be sorted. It should be as it is, i.e. only the empty values should move to the end of an array.

我需要的东西。我的例子显示。

I need exactly what my examples show.

推荐答案

有在这个线程已经好多/更优雅的答案,但这个工程太:

There are much better/more elegant answers in this thread already, but this works too:

//strip empties and move to end
foreach ($givenArray as $key => $value)
{ 
    if ($value === "")
    { 
        unset($givenArray[$key]);
        $givenArray[] = $value;
    }
}

// rebuild array index
$givenArray = array_values($givenArray);

codePAD演示

这篇关于PHP - 如何数组的空值移动到它的最后位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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