Move array item with certain key to the first posi

2020-02-12 01:58发布

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

Input:

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

Output:

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

标签: php arrays
8条回答
Emotional °昔
2楼-- · 2020-02-12 02:20
<?php
$key = 10;
$arr = array(0,1,2,3);
array_unshift($arr,$key);
var_dump($arr) //10,0,1,2,3
?>
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-12 02:22
$tgt = 10;
$key = array_search($tgt, $arr);
for($i=0;$i<$key;$i++)
{
   $temp = $arr[$i];
   $arr[$i] = $tgt;
   $tgt = $temp;
}

After this simple code, all you need to do is display the re-arranged array. :)

查看更多
登录 后发表回答