数组在最后发送空值并重新排列数组 [英] Array to send empty value at last and rearrange array

查看:70
本文介绍了数组在最后发送空值并重新排列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组。

如果之间的任何数组值变为空或null,我希望该空值之后的任何值都可以在该空数组中移动。

If any array values within between becomes empty or null I want any after that empty value to be shifted within that empty array.

我通过取消设置数组使用了foreach循环,但问题是,如果存在0值,则该数字大于0则排在第二位,然后大于0则移位在第一名。

I used a foreach loop by unsetting an array but the problem is that if there is a 0 value the number greater then 0 shifts at second place and greater then 0 values shifts at 1st place.

我不知道这是怎么回事。

I do not know how come this is happening.

这是我的代码:

$val1     = $this->input->post('current');
$val2     = $this->input->post('graph1');
$val3     = $this->input->post('graph2');
$val4     = $this->input->post('graph3');
$val5     = $this->input->post('graph4');
$filter   = array($val1, $val2, $val3, $val4, $val5);
//array(0, '', 2, '', '')
foreach ($filter as $key => $value) { 
    if (empty($value)) { 
        unset($filter[$key]);
        $filter[] = $value;
    }
}

$filter_new = array_values($filter);
//array(2, 0, '', '', '') 


推荐答案

您的问题是 empty(0)返回 TRUE ,因此如果您的 0 值传递到第二个位置。

Your problem is empty(0) returns TRUE, so it's normal if your 0 value pass on 2nd position.

尝试一下:

    foreach ($filter as $key => $value) { 
        if ($value == '') { 
            unset($filter[$key]);
            $filter[] = $value;
        }
    }

    $filter_new = array_values($filter);
    //array(0, 2, '', '', '') 

这篇关于数组在最后发送空值并重新排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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