Diddling with arrays with numeric string keys

后端 未结 2 1274
名媛妹妹
名媛妹妹 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:03

    You can try to remove it with array_splice(), if you know its offset ( foreach (...) { $offset++; ... } ), but storing data in an arrays like this, is really not a good idea. You should convert these objects to array with foreach:

    foreach ( $obj as $key => $value )
        $array[$key] = $value;
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题