2016-02-12 78 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)

注意位置參數是可選的,只是將元素移動到數組的開頭。此外,它可能是負整數,在這種情況下,元素的位置(索引)從其結尾計算。

有一個驗證,確保元素存在於數組中,並且新位置提供爲整數值。

有關更多詳細信息,請參閱代碼註釋。