这里是整齐的功能操作任何现有元素的数组中的位置(索引):
$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