PHP - 使用array_filter从哈希表(数组)中删除项目

ada*_*dam 3 php arrays array-filter

在PHP中,我知道一旦将项目放入数组中,就没有正式的方法来删除它们.但对我的问题必须有一个"最好的方法"解决方案.我相信这可能在于array_filter功能.

基本上,我有一个购物车对象,可以将项目存储在哈希表中.想象一下,你一次只能购买任何一件物品.

我做

add_item(1);
add_item(2);
remove_item(1);
Run Code Online (Sandbox Code Playgroud)

get_count() 仍然返回2.

var $items;


function add_item($id) {
    $this->items[$id] = new myitem($id);
}

function remove_item($id) {
    if ($this->items[$id]) {
        $this->items[$id] = false;
        return true;
    } else {    
        return false;
    }
}


function get_count() {
    return count($this->items);
}
Run Code Online (Sandbox Code Playgroud)

人们认为在get_count中使用的最佳方法是什么?我无法弄清楚使用array_filter的最佳方法,它只是不返回false值(不编写单独的回调).

谢谢 :)

Pet*_*ley 8

没有官方的方式?当然有! 不设置!

<?php

class foo
{
    var $items = array();


    function add_item($id) {
            $this->items[$id] = new myitem($id);
    }

    function remove_item($id)
    {
        unset( $this->items[$id] );

    }


    function get_count() {
            return count($this->items);
    }
}

class myitem
{
    function myitem( $id )
    {
        // nothing
    }
}

$f = new foo();

$f->add_item( 1 );
$f->add_item( 2 );

$f->remove_item( 1 );

echo $f->get_count();
Run Code Online (Sandbox Code Playgroud)

还有,这是PHP4吗?因为如果没有,你应该研究一些SPL的东西,比如ArrayObject,或者至少是CountableArrayAccess接口.

编辑

这是一个直接使用接口的版本

<?php

class foo implements ArrayAccess, Countable
{
    protected $items = array();

    public function offsetExists( $offset )
    {
        return isset( $this->items );
    }

    public function offsetGet( $offset )
    {
        return $this->items[$offset];
    }

    public function offsetSet( $offset, $value )
    {
        $this->items[$offset] = $value;
    }

    public function offsetUnset( $offset )
    {
        unset( $this->items[$offset] );
    }

    public function count()
    {
        return count( $this->items );
    }

    public function addItem( $id )
    {
        $this[$id] = new myitem( $id );
    }
}

class myitem
{
    public function __construct( $id )
    {
        // nothing
    }
}

$f = new foo();

$f->addItem( 1 );
$f->addItem( 2 );
unset( $f[1] );

echo count( $f );
Run Code Online (Sandbox Code Playgroud)

这是一个作为ArrayObject实现的版本

<?php

class foo extends ArrayObject
{
    public function addItem( $id )
    {
        $this[$id] = new myitem( $id );
    }
}

class myitem
{
    public function __construct( $id )
    {
        // nothing
    }
}

$f = new foo();

$f->addItem( 1 );
$f->addItem( 2 );
unset( $f[1] );

echo count( $f );
Run Code Online (Sandbox Code Playgroud)


Mar*_*rio 5

if ($this->items[$id]) {
Run Code Online (Sandbox Code Playgroud)

可能会返回警告,应该使用array_key_exists或isset.

unset()似乎比删除项目时分配false更清晰(也将摆脱你的计数问题).