简体   繁体   中英

php reorder array of strings

I have an array of strings corresponding to names of images in a directory.

Here is an example:

    array(3) { [0]=> string(5) "3.png" [1]=> string(5) "2.jpg" [2]=> string(6) "4.jpeg" }

How could I reorder that array so that the numbers before the extensions increases such as the example below:

    array(3) { [0]=> string(5) "2.jpg" [1]=> string(5) "3.png"  [2]=> string(6) "4.jpeg" }

use sort function:

$array = array(
    '2.png',
    '4.png',
    '1.png',
);

sort($array);

print_r($array);

Output:

Array ( [0] => 1.png [1] => 2.png [2] => 4.png )

For more detail have a look at: PHP Array Sorting

Here is the neat function to manipulate the position (index) of any existing element in the array:

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

The output:

Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )

Array ( [0] => a [1] => c [2] => b [3] => d [4] => e )

Notice that the position parameter is optional and if omitted the function just moves the element to the beginning of the array. Also, it may be negative integer in which case the position (index) of the element is calculated from its end.

There is a validation that makes sure the element exists in the array, and that the new position is provided as integer value.

See the code comments for more details.

Use sort() or 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

you can find more here: http://php.net/manual/en/array.sorting.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM