PHP如何对arrayObject进行array

编程入门 行业动态 更新时间:2024-10-17 09:43:35
PHP如何对arrayObject进行array_unshift(PHP how to array_unshift on an arrayObject)

如标题所述,如何在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.

更多推荐

本文发布于:2023-08-06 20:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PHP   arrayObject   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!