PHP - 通过重新排列特定索引数组 [英] PHP - Rearrange array by specific index

查看:105
本文介绍了PHP - 通过重新排列特定索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有以下的code:

  $ =样品阵列(苹果,桔子,香蕉,葡萄);

我要重新排列这个数组,通过 $样本[2] 新的 $样本[0] ,同时保持整个阵列的顺序相同。

输出应该是:

 阵列([0] =>香蕉[1] =>葡萄[2] =>苹果[3] =>橙色)


解决方案

使用的 array_shift() 多次,因为你需要...

  $ =样品阵列('苹果','橙','香蕉','葡萄');$水果= array_shift($样品);
$样本[] = $水果;
//现在$样品将阵列('橙色','香蕉','葡萄','苹果');

所以说,你想一个函数:

 函数rearrange_array($数组$键){
    而($键大于0){
        $ TEMP = array_shift($数组);
        $数组[] = $温度;
        $ key--;
    }
    返回$阵列;
}

现在,使用 rearrange_array($样品,2)可以将样品阵列重新安排到所需的输出。

For example I have the following code:

$sample = array(apple, orange, banana, grape);

I want to rearrange this array, by making $sample[2] the new $sample[0], while keeping the same order throughout the array.

Output should be:

Array ( [0] => banana [1] => grape [2] => apple [3] => orange) 

解决方案

Use array_shift() as many times as you need...

$sample = array('apple', 'orange', 'banana', 'grape');

$fruit = array_shift($sample);
$sample[] = $fruit;
// now $sample will be array('orange', 'banana', 'grape', 'apple');

So say you want to make a function:

function rearrange_array($array, $key) {
    while ($key > 0) {
        $temp = array_shift($array);
        $array[] = $temp;
        $key--;
    }
    return $array;
}

Now, using rearrange_array($sample, 2) you can rearrange the sample array to your desired output.

这篇关于PHP - 通过重新排列特定索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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