在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