删除数组空值

时间:2011-04-20 08:00:04

标签: php

 foreach ($this->CsInventory as $value)
    {

     print_r($value) // print 1
    $vname = $value[] = $value['VesselName']; 
    $total = $value[] = $value['Total']; 
    $Box = $value[] = $value['Box']; 

        print_r($value); // print 2

        $rdata .= '<td>'.$vname.'</td>
          <td>'.$total.'</td>
             <td>'.$Box.'</td>';                 
    }

打印1

Array
(
    [VesselName] => MARIANNE
    [Total] => 13838
    [Box] => 1156
)
Array
(
    [Box] => 154
)
Array
(
    [Box] => 3825
)
Array
(
    [Box] => 50571
)

打印2

Array
(
    [VesselName] => MARIANNE
    [Total] => 15452
    [Box] => 1156
    [0] => MARIANNE
    [1] => 15452
    [2] => 1156
)
Array
(
    [Box] => 2276
    [0] => 
    [1] => 
    [2] => 2276
)
Array
(
    [Box] => 3825
    [0] => 
    [1] => 
    [2] => 3825
)
Array
(
    [Box] => 49235
    [0] => 
    [1] => 
    [2] => 49235
)

我如何删除数组中的空值?我尝试了很多方法,但我可以得到任何解决方案..所以决定在论坛这里?

3 个答案:

答案 0 :(得分:4)

我会尽力减少努力。

foreach ($this->CsInventory as $value) 
    { 
        foreach ($value as $key => $item)
        {
             $value[] = $item;
             $rdata .= "<td>$item</td>";

        }

       print_r($value)                  
    } 

作为一般性评论,不确定为什么要将自治值添加回$values堆栈,最好使用不同的数组。

答案 1 :(得分:1)

如果您想要摆脱特定的数组元素,可以使用unset($array[$key]);

您还可以使用

阻止他们首先进入阵列
if($value['VesselName']) {$vname = $value[] = $value['VesselName'];}

而不是简单

$vname = $value[] = $value['VesselName'];

答案 2 :(得分:0)

function array_remove_empty($arr){
    $narr = array();
    while(list($key, $val) = each($arr)){
        if (is_array($val)){
            $val = array_remove_empty($val);
            // does the result array contain anything?
            if (count($val)!=0){
                // yes :-)
                $narr[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}

array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)