如标题所述,如何在arrayObject上执行array_unshift() , array_push()是通过执行arrayObject->append()来获得的,但是如何解决unshift?
编辑:我忘了提到的是,我还需要在这种特殊情况下保存现有的密钥。
As stated in the title, How do you perform an array_unshift() on a arrayObject, array_push() is obtained by doing an arrayObject->append() but what about unshift ?
Edit: What I've forgot to mention is that i also need in this particular case to preserve existing keys.
最满意答案
ArrayObject的API没有任何直接完成此功能的功能。 你有其他几个选择:
手动将每个元素移动1,然后在索引0处设置新值(仅当您使用数字索引ArrayObject时)。 $tmp = NULL; for ($i = 0; $arrayObject->offsetExists($i + 1); $i++) { $tmp = $arrayObject->offsetGet($i + 1); $arrayObject->offsetSet($i + 1, $arrayObject->offsetGet($i)); } $arrayObject->offsetSet($i, $tmp); $arrayObject->offsetSet(0, $new_value); 编写一个从ArrayObject派生的类并添加一个函数prepend (实现可以是下面的一个)。 提取一个数组,调用array_unshift()并用修改后的数组创建一个新的ArrayObject : $array = $arrayObject->getArrayCopy(); array_unshift($array, $new_value); $arrayObject->exchangeArray($array);@Dmitry, @soulmerge your answers was good regarding the initial question but was missing the requirement in my edit, but they point me in the right direction to achieve what i was expected here's the solution we came with here at work: (work for php>=5.1)
public function unshift($value){ $tmp = $this->getArrayCopy(); $tmp = array($value) + $tmp; $this->exchangeArray($tmp); return $this; }these exemple is not exactly the same as the final solution we needed as for our particular arrayObject. We use a given key in array values as key for the values (think of using database rowId as index for each value in the collection). let's call this value "key" here's what the actual array struct looks like:
array( key1 => array(key=>key1,val1=>val1,val2=>val2...), key2 => array(key=>key2,val1=>val1_2,val2=>val2_2...), ... );so our solution looks more something like this:
public function unshift($value){ $tmp = $this->getArrayCopy(); $tmp = array($value['key'],$value) + $tmp; $this->exchangeArray($tmp); return $this; }thank's for your answers, if you find a way that work in php5.0 too i'm still interested.
更多推荐
发布评论