在 PHP 中将数组元素移动到顶部
$arr = array(
'a1'=>'1',
'a2'=>'2'
);
我需要将 a2 移到顶部,并保留 a2
作为键,我该如何继续下去,我似乎无法想出一种方法而不搞砸一些东西:)
$arr = array(
'a1'=>'1',
'a2'=>'2'
);
I need to move the a2 to the top, as well as keep the a2
as a key how would I go on about it I can't seem to think a way without messing something up :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个可以正确使用数字键和字符串键的解决方案:
它之所以有效,是因为 PHP 中的数组是有序映射。
顺便说一句,要将项目移动到底部,请使用:
Here is a solution which works correctly both with numeric and string keys:
It works because arrays in PHP are ordered maps.
Btw, to move an item to bottom use:
您可以通过以下方式实现:
You can achieve that this way:
试试这个:
结果:
try this:
result:
这是一个简单的单行代码,可以使用 array_splice() 和 union 运算符来完成此操作:
编辑:
回想起来,我不确定为什么我要这样做不仅仅是这样做:
更干净、更容易而且可能更快。
Here's a simple one liner to get this done with
array_splice()
and theunion
operator:Edit:
In retrospect I'm not sure why I wouldn't just do this:
Cleaner, easier and probably faster.
您还可以查看 array_multisort 这可以让您使用一个数组对另一个进行排序。例如,这可以允许您将硬编码的值顺序外部化到配置文件中。
输出:
You can also look at array_multisort This lets you use one array to sort another. This could, for example, allow you to externalize a hard-coded ordering of values into a config file.
Outputs: