PHP:'旋转'的阵? [英] PHP: 'rotate' an array?

查看:153
本文介绍了PHP:'旋转'的阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是它可以很容易地旋转在PHP中的数组?

is it possible to easily 'rotate' an array in PHP ?

就像这样:
1,2,3,4 - > 2,3,4,1

Like this: 1, 2, 3, 4 -> 2, 3 ,4 ,1

是否有某种内置PHP函数这个?

Is there some kind of built-in PHP function for this?

推荐答案

目前大多数的答案是正确的,但只有当你不关心你的指标:

Most of the current answers are correct, but only if you don't care about your indices:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
array_push($arr, array_shift($arr));
print_r($arr);

输出:

Array
(
    [baz] => qux
    [wibble] => wobble
    [0] => bar
)

要preserve的指数,你可以这样做:

To preserve your indices you can do something like:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');

$keys = array_keys($arr);
$val = $arr[$keys[0]];
unset($arr[$keys[0]]);
$arr[$keys[0]] = $val;

print_r($arr);

输出:

Array
(
    [baz] => qux
    [wibble] => wobble
    [foo] => bar
)

也许有人可以做旋转比我四线方法更简洁,但这个工程呢。

Perhaps someone can do the rotation more succinctly than my four-line method, but this works anyway.

这篇关于PHP:'旋转'的阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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