移动数组元素在PHP中的新指标 [英] Move an array element to a new index in PHP

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

问题描述

我在寻找一个简单的函数数组元素移动到阵列中的一个新的位置,并重新排序的指标,以便有序列中没有间隙。它并不需要与关联数组工作。任何人都有想法,这一个?

  $ a =阵列(0 =>'一',1 =>'C',2 =>'D',3 =>'B',4 = GT;'E');
的print_r(moveElement(3,1))
//应该输出[0 =>'一',1 =>'B',2 =>'C',3 =>D,4 =>'E']


解决方案

至于评论,2 array_splice ,甚至有没有必要重新编号:

  $阵列= [0 =>'一',1 =>'C',2 =>'D',3 =>'B',4 = >'E'];功能moveElement(安培; $阵列,$ A,$ B){
    $ OUT = array_splice($数组,$ A,1);
    array_splice($数组$ B,0,$出);
}moveElement($阵列,3,1);

结果:

  [0 =>'一',1 =>'B',2 =>'C',3 =>D,4 =>' E'];

I'm looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt need to work with associative arrays. Anyone got ideas for this one?

$a = array(0=>'a', 1=>'c', 2=>'d', 3=>'b', 4=>'e');
print_r(moveElement(3,1))
//should output [0=>'a', 1=>'b', 2=>'c', 3=>'d', 4=>'e']

解决方案

As commented, 2x array_splice, there even is no need to renumber:

$array = [0=>'a', 1=>'c', 2=>'d', 3=>'b', 4=>'e'];

function moveElement(&$array, $a, $b) {
    $out = array_splice($array, $a, 1);
    array_splice($array, $b, 0, $out);
}

moveElement($array, 3, 1);

Result:

[0=>'a', 1=>'b', 2=>'c', 3=>'d', 4=>'e'];

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

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