PHP 如何对 arrayObject 进行 array_unshift
正如标题中所述,如何在 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ArrayObject 的 API 没有任何函数可以直接完成此操作。您还有其他几个选项:
ArrayObject
派生的类,并添加一个prepend
函数(实现可以是下面的)。array_unshift()
并使用修改后的数组创建一个新的ArrayObject
:The API of ArrayObject does not have any function to accomplish this directly. You have several other options:
ArrayObject
and add a functionprepend
(implementation could be the one below).array_unshift()
and create a newArrayObject
with the modified array:ArrayObject 中没有这样的功能,但您可以对其进行子类化以添加您需要的任何内容。试试这个:
There is no such functionality in ArrayObject, but you can subclass it to add whatever you need. Try this:
@Dmitry,@soulmerge,关于最初的问题,您的答案很好,但缺少我编辑中的要求,但它们为我指明了正确的方向,以实现我的预期,这是我们在工作中提供的解决方案:(适用于 php> ;=5.1)
这些示例与我们特定 arrayObject 所需的最终解决方案并不完全相同。我们使用数组值中的给定键作为值的键(考虑使用数据库 rowId 作为集合中每个值的索引)。让我们称这个值为“key”,这就是实际的数组结构的样子:
所以我们的解决方案看起来更像这样:
谢谢你的回答,如果你找到一种在 php5.0 中也能工作的方法,我仍然感兴趣.
@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)
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:
so our solution looks more something like this:
thank's for your answers, if you find a way that work in php5.0 too i'm still interested.
这对我有用。与array_merge()
this works for me. with array_merge()