用特定的键将数组项移动到数组中的第一个位置,PHP [英] Move array item with certain key to the first position in an array, PHP

查看:909
本文介绍了用特定的键将数组项移动到数组中的第一个位置,PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,将键选择的数组元素移动到第一个位置的最优雅的方法是什么?

What's the most elegant way in PHP to move an array element chosen by key to the first position?

输入:

$arr[0]=0;
$arr[1]=1;
$arr[2]=2;
....
$arr[n]=n;
$key=10;

输出:

$arr[0]=10;
$arr[1]=0;
$arr[2]=1;
$arr[3]=2;
....
$arr[n]=n;

推荐答案

无需取消设置键.为了简短起见,请按照以下步骤操作

No need to unset keys. To keep it short just do as follow

//appending $new in our array 
array_unshift($arr, $new);
//now make it unique.
$final = array_unique($arr);

Demo

这篇关于用特定的键将数组项移动到数组中的第一个位置,PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆