如何从索引值重新排序数组

时间:2016-10-20 17:45:44

标签: php arrays sorting

我正在寻找一种使用索引值重新排序字符串/数组的方法。

示例:字符串(1,2,3,4,5)更改为(1,5,2,3,4)

$string = "1,a,v,v|2,b,v,v|3,c,v,v";

// Convert string to array first...
$sections = explode ('|', $string);

$current_index = "1";
$new_index = "2";
$arrReorder = array();

foreach($sections as $key => $val){
  if ($key = $current_index) {
    $arrReorder[$new_index] = $val;
  }
  else {
    $arrReorder[$key] = $val;
  }
}

$new_string = implode("|", $arrReorder);
echo $new_string;

$new_string应输出" 1,a,v,v | 3,c,v,v | 2,b,v,v"

1 个答案:

答案 0 :(得分:0)

I found a solution for anyone trying to do the same thing:

$string = "1,2,3";
// Convert string to array first...
$sections = explode ('|', $string);

function array_move(&$sections, $oldpos, $newpos) {
    if ($oldpos==$newpos) {return;}
    array_splice($sections,max($newpos,0),0,array_splice($sections,max($oldpos,0),1));
}

array_move($sections, 0, 2);
print_r($sections);