php数组是哈希表吗,PHP – 使用array_filter从哈希表(数组)中删除项目

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

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

我做

add_item(1);

add_item(2);

remove_item(1);

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);

}

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

谢谢 :)

解决方法:

没有官方的方式?当然有! Unset!

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();

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

编辑

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

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 );

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

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 );

标签:php,arrays,array-filter

来源: https://codeday.me/bug/20190713/1448654.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值