Diddling with arrays with numeric string keys

后端 未结 2 1280
名媛妹妹
名媛妹妹 2021-01-24 09:23

To understand why I\'m asking this, read this and the comments under it. Consider the following code:

$obj = new stdClass;
$obj->{10} = \'Thing\';

$objArray          


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-24 10:11

    Following pozs's advice, here's the resulting offsetUnset(). I also added a new offsetSet() which supports adding numeric keys.

    public function offsetUnset($offset)
    {
        $off = 0;
    
        foreach ($this->arr as $key => $value)
        {
            if ($key === $offset)
            {
                array_splice($this->arr, $off, 1);
                return;
            }
            $off++;
        }       
    }
    
    public function offsetSet($offset, $value)
    {
        foreach($this->arr as $key => &$thevalue)
        {
            if ($key === $offset)
            {
                $thevalue = $value;
                return;
            }
        }
    
        // if $offset is *not* present...
        if ($offset === null)
        {
            $this->arr[] = $value;
        }
        // it's a numeric string key, now we have to hack it
        else if (strval(intval($offset)) === $offset)
        {
            // create new array via loophole:
            $tempObj = new stdClass;
            $tempObj->{$offset} = $value;
    
            // append to old array (+= doesn't create copies)
            $this->arr += (array) $tempObj;
            unset($tempObj);
        }
        // we are dealing with a normal key
        else
        {
            $this->arr[$offset] = $value;
        }
    }
    

    I've officially defeated PHP. Yay!

提交回复
热议问题