将 PHP 数组中的值移动到数组的开头 [英] Move Value in PHP Array to the Beginning of the Array

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

问题描述

我有一个类似这样的 PHP 数组:

I have a PHP array similar to this:

0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"

我想将黄色移动到索引 0.我该怎么做?

I want to move yellow to index 0. How do I do this?

我的问题是如何将这些元素中的任何一个移动到开头?我如何将绿色移动到索引 0,或蓝色移动到索引 0?这个问题不仅仅关于将最后一个元素移到开头.

My question is how do I move any one of these elements to the beginning? How would I move green to index 0, or blue to index 0? This question is not exclusively about moving the last element to the beginning.

推荐答案

这对我来说似乎是最简单的方法.您可以将任何位置移动到开头,而不仅仅是最后一个(在本例中,它会将蓝色移动到开头).

This seems like the simplest way to me. You can move any position to the beginning, not just the last (in this example it moves blue to the beginning).

$colours = array("red", "green", "blue", "yellow");

$movecolour = $colours[2];
unset($colours[2]);
array_unshift($colours, $movecolour);

这篇关于将 PHP 数组中的值移动到数组的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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