欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

如何找出PHP对象数组的差值?

程序员文章站 2022-03-27 16:57:24
...
《深入PHP 面向对象、模式与实践》的159页有下面的代码。
这儿是演示组合模式,removeUnit那个方法里用到了array_udiff函数。作者的本意是这样可以从 $units 属性里去除$unit 对象。我试了发现不起作用,关键就在$units参数里存的是对象,对象做比较时不能排序,所以就失败了。大家有没有好的方法可以从数组里排除掉一个对象吗?


class Army extends Unit{

private $units = array();

function addUnit(Unit $unit){
    if(in_array($unit, $this->units, true)){
        return;
    }   
    $this->units[] = $unit;
}   

function removeUnit(Unit $unit){
    $this->units = array_udiff($this->units, array($unit), function ($a, $b) {
        return ($a === $b) ? 0: 1;}); 
}   

function bombardStrength(){
    $ret = 0;
    foreach($this->units as $unit){
        $ret += $unit->bombardStrength();
    }   
    return $ret;
}   

}

$army = new Army;

$archer = new Archer();
//$archer->addUnit(new Archer);
$army->addUnit($archer);
$army->addUnit($archer);
$army->addUnit(new Archer);
$army->addUnit(new LaserCannonUnit);
$army2 = new Army();
$army2->addUnit(new Archer);
$army2->addUnit($archer);
$army2->addUnit($archer);
$army2->removeUnit($archer);
$army->addUnit($army2);
$army->addUnit($army2);

print_r($army);
echo $army->bombardStrength()."\n";

$army->removeUnit($army2);
$army->removeUnit($army2);
$army->removeUnit($army2);
$army->removeUnit($archer);
echo $army->bombardStrength();
print_r($army);

回复内容:

《深入PHP 面向对象、模式与实践》的159页有下面的代码。
这儿是演示组合模式,removeUnit那个方法里用到了array_udiff函数。作者的本意是这样可以从 $units 属性里去除$unit 对象。我试了发现不起作用,关键就在$units参数里存的是对象,对象做比较时不能排序,所以就失败了。大家有没有好的方法可以从数组里排除掉一个对象吗?


class Army extends Unit{

private $units = array();

function addUnit(Unit $unit){
    if(in_array($unit, $this->units, true)){
        return;
    }   
    $this->units[] = $unit;
}   

function removeUnit(Unit $unit){
    $this->units = array_udiff($this->units, array($unit), function ($a, $b) {
        return ($a === $b) ? 0: 1;}); 
}   

function bombardStrength(){
    $ret = 0;
    foreach($this->units as $unit){
        $ret += $unit->bombardStrength();
    }   
    return $ret;
}   

}

$army = new Army;

$archer = new Archer();
//$archer->addUnit(new Archer);
$army->addUnit($archer);
$army->addUnit($archer);
$army->addUnit(new Archer);
$army->addUnit(new LaserCannonUnit);
$army2 = new Army();
$army2->addUnit(new Archer);
$army2->addUnit($archer);
$army2->addUnit($archer);
$army2->removeUnit($archer);
$army->addUnit($army2);
$army->addUnit($army2);

print_r($army);
echo $army->bombardStrength()."\n";

$army->removeUnit($army2);
$army->removeUnit($army2);
$army->removeUnit($army2);
$army->removeUnit($archer);
echo $army->bombardStrength();
print_r($army);

直接循环和unset解决了。

foreach($this->units as $k => $u){ 
         if($u === $unit){
             unset($this->units[$k]);
         }
     }
相关标签: php