dqdtgiw4736 2012-11-02 07:15
浏览 97
已采纳

从数组中删除对象; 如何避免空值

I have an array that is a object which I carry in session lifeFleetSelectedTrucksList I also have objects of class fleetUnit

class fleetUnit {
    public $idgps_unit = null;
    public $serial = null;
}

class lifeFleetSelectedTrucksList {
    public $arrayList = array();
}

$listOfTrucks = new lifeFleetSelectedTrucksList(); //this is the array that I carry in session
if (!isset($_SESSION['lifeFleetSelectedTrucksList'])) {
    $_SESSION['lifeFleetSelectedTrucksList'] == null; //null the session and add new list to it.
} else {
    $listOfTrucks = $_SESSION['lifeFleetSelectedTrucksList'];
}

I use this to remove element from array:

$listOfTrucks = removeElement($listOfTrucks, $serial);

And this is my function that removes the element and returns the array without the element:

function removeElement($listOfTrucks, $remove) {
    for ($i = 0; $i < count($listOfTrucks->arrayList); $i++) {
        $unit = new fleetUnit();
        $unit = $listOfTrucks->arrayList[$i];
        if ($unit->serial == $remove) {
            unset($listOfTrucks->arrayList[$i]);
            break;
        } elseif ($unit->serial == '') {
            unset($listOfTrucks->arrayList[$i]);
        }
    }
    return $listOfTrucks;
}

Well, it works- element gets removed, but I have array that has bunch of null vaues instead. How do I return the array that contains no null elements? Seems that I am not suing something right.

  • 写回答

2条回答 默认 最新

  • drozwmi5440 2012-11-02 07:21
    关注

    I think what you mean is that the array keys are not continuous anymore. An array does not have "null values" in PHP, unless you set a value to null.

    $array = array('foo', 'bar', 'baz');
    // array(0 => 'foo', 1 => 'bar', 2 => 'baz');
    
    unset($array[1]);
    
    // array(0 => 'foo', 2 => 'baz');
    

    Two approaches to this:

    1. Loop over the array using foreach, not a "manual" for loop, then it won't matter what the keys are.
    2. Reset the keys with array_values.

    Also, removing trucks from the list should really be a method of $listOfTrucks, like $listOfTrucks->remove($remove). You're already using objects, use them to their full potential!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集