這裏是整齊的功能操作任何現有元素的數組中的位置(索引):
$sampleArray = array('a', 'b', 'c', 'd', 'e');
print_r($sampleArray);
print_r(arrayMoveElement('c',$sampleArray,1));
exit;
function arrayMoveElement($element, &$array, $position=0){
$index = array_search($element, $array); // Search for the element in the array and returns its current index
if($index == false){ // Make sure the element is present in the array
return false;
}
else{
unset($array[$index]); // Removes the element from the array
$array = array_values($array); // Re-sorts the indexes
if(!is_int($position)){return false;} // Position of the element that should be inserted must be a valid integer (index)
array_splice($array, $position, 0, $element); // Inserts the element to the desired position (index) starting from 0
return $array;
}
}// END function arrayMoveElementFirst($element, &$array){
輸出:
Array([0] => a [1] => b [2] => c [3] => d [4] => e)
陣列([0] => a [1] => c [2] => b [3] => d [4] => e)
注意位置參數是可選的,只是將元素移動到數組的開頭。此外,它可能是負整數,在這種情況下,元素的位置(索引)從其結尾計算。
有一個驗證,確保元素存在於數組中,並且新位置提供爲整數值。
有關更多詳細信息,請參閱代碼註釋。
聽起來像分揀,是嗎? – AbraCadaver