PHP - Delete Item from Hash Table (array) using array_filter -
In PHP, I know that there is no official way to remove objects when they are inserted into an array,
< P> But my problem should be a "best way" solution. I believe this can be located in the
array_filter function. Essentially, I have a shopping cart object that stores items in a hashtable. Imagine that you can buy any one item only at one time.
I do
add_item (1); Add_item (2); Remove_item (1); get_count () still returns 2.
var $ items; Function add_item ($ id) {$ this- & gt; Items [$ id] = new mitim ($ id); } Function remove_item ($ id) {if ($ this-> item [$ id]) {$ this- & gt; Item [$ id] = false; Back true; } Other {return false; }} Function get_count () {return calculation ($ this-> item); } What do people think is the best way to use in get_count? I can not understand the best way to use array_filter, which does not just return false values (without writing separate callback).
thanks :)
Is there no official way? Sure there is! !
& lt ;? Php square foo {var $ items = array (); Function add_item ($ id) {$ this- & gt; Items [$ id] = new mitim ($ id); } Function remove_item ($ id) {unset ($ this-> item [$ id]); } Function get_count () {return calculation ($ this-> item); }} Class myitem {function myitem ($ id) {// nothing}} $ f = new foo (); $ F- & gt; Add_item (1); $ F- & gt; Add_item (2); $ F- & gt; Remove_item (1); Repeat $ f-> get_count (); Besides, is it PHP4? Because if not, you should look at some SPL stuff or at least and look like an interface.
Edit
There is a version here by using the interface
& lt ;? Php square foo applies ArrayAccess, Countable {secure $ items = array (); Public Function OffsetExists (Offset of $) {Return Pratt ($ ----- Item); } Public function offset gadget ($ offset) {return $ this-> Items [$ offset]; } Public function offsetset ($ offset, $ value) {$ this- & gt; Item [$ offset] = $ value; } Public function offset offset ($ offset) {unset ($-> item [offset offset]); } Public Function Count () {Calculation of Return ($ this-> Item); } Public function addItem ($ id) {$ this [$ id] = new myitem ($ id); }} Class myitem {public function __construct ($ id) {// nothing}} $ f = new foo (); $ F- & gt; Add Atom (1); $ F-> AdiTom (2); Unset ($ F [1]); Resonance count ($ F); And here ArrayObject
& lt ;? Php class is a version of the implementation of foo ArrayObject {public function addItem ($ id) {$ this [$ ID] = new mitim ($ ID); }} Class myitem {public function __construct ($ id) {// nothing}} $ f = new foo (); $ F- & gt; Add Atom (1); $ F-> AdiTom (2); Unset ($ F [1]); Resonance count ($ F);
Comments
Post a Comment