Deleting an element from an array in PHP

后端 未结 30 3265
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 06:48

    I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):

    class obj {
        protected $fields = array('field1','field2');
        protected $field1 = array();
        protected $field2 = array();
        protected loadfields(){}
        // This will load the $field1 and $field2 with rows of data for the column they describe
        protected function clearFields($num){
            foreach($fields as $field) {
                unset($this->$field[$num]);
                // This did not work the line below worked
                unset($this->{$field}[$num]); // You have to resolve $field first using {}
            }
        }
    }
    

    The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.

提交回复
热议问题