2016-02-12 77 views
1

我有一个字符串数组,对应于目录中图像的名称。php重新排列字符串数组

下面是一个例子:

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" } 
+0

听起来像分拣,是吗? – AbraCadaver

回答

1

使用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 Array Sorting

+0

哦,我正在寻找复杂!像分离之前的点,将其转换为整数等...很好的功能。 – michltm

0

用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

1

这里是整齐的功能操作任何现有元素的数组中的位置(索引):

$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)

注意位置参数是可选的,只是将元素移动到数组的开头。此外,它可能是负整数,在这种情况下,元素的位置(索引)从其结尾计算。

有一个验证,确保元素存在于数组中,并且新位置提供为整数值。

有关更多详细信息,请参阅代码注释。