2016-10-20 5 views
0

インデックス値を使用して文字列/配列を並べ替える方法を探しています。インデックス値から配列を並べ替える方法

例:文字列(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、V、V | 3、C、V、V | 2、B、V、V」

答えて

0

私は同じことをやろうとしている人のための解決策を見つけた:

$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); 
関連する問題