将数组元素移动到 PHP 中的新索引 [英] Move an array element to a new index in PHP

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

问题描述

我正在寻找一个简单的函数来将数组元素移动到数组中的新位置并对索引重新排序,以便序列中没有间隙.它不需要使用关联数组.有人对此有想法吗?

$a = 数组(0 =>'一种',1 =>'C',2 =>'d',3 =>'b',4 =>'e',);打印_r(移动元素(3,1))//应该输出[0 =>'一种',1 =>'b',2 =>'C',3 =>'d',4 =>'e']

解决方案

如评论中所说,2x array_splice,甚至不需要重新编号:

$array = [0 =>'一种',1 =>'C',2 =>'d',3 =>'b',4 =>'e',];函数 moveElement(&$array, $a, $b) {$out = array_splice($array, $a, 1);array_splice($array, $b, 0, $out);}moveElement($array, 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天全站免登陆