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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀