在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