我有一个字符串数组,对应于目录中的图像名称。
下面是一个示例:
array(3) { [0]=> string(5) "3.png" [1]=> string(5) "2.jpg" [2]=> string(6) "4.jpeg" }
我怎样才能对该数组重新排序,以便扩展名之前的数字增加,如下例所示:
array(3) { [0]=> string(5) "2.jpg" [1]=> string(5) "3.png" [2]=> string(6) "4.jpeg" }
使用sort
函数:
$array = array(
'2.png',
'4.png',
'1.png',
);
sort($array);
print_r($array);
输出:
Array ( [0] => 1.png [1] => 2.png [2] => 4.png )
有关更多详细信息,请查看: PHP 数组排序
下面是一个简洁的函数,用于操作数组中任何现有元素的位置(索引):
$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){
输出:
数组 ( [0] => a [1] => b [2] => c [3] =>d [4] => e )
数组 ( [0] => a [1] => c [2] => b [3] =>d [4] => e )
请注意,position 参数是可选的,如果省略,该函数只会将元素移动到数组的开头。此外,它可能是负整数,在这种情况下,元素的位置(索引)是从其末尾计算的。
有一个验证可确保元素存在于数组中,并且新位置作为整数值提供。
有关更多详细信息,请参阅代码注释。
使用 sort() 或 asort();
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "'n";
}
?>
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
您可以在此处找到更多信息:http://php.net/manual/en/array.sorting.php