简体   繁体   中英

sorting a numeric php array

I have a php array $data which contains a list of files

   [3945] => 6358--338940.txt
   [3946] => 6357--348639.txt
   [3947] => 6356--348265.txt
   [3948] => 6354--345445.txt
   [3949] => 6354--340195.txt

I need to order the array using the the numeric value after -- in the filename. How to do that ?

Thanks Regards

If you want an algorithm, the good way could be to :

Here is the code to do so :

<?php
    /* your code here */

    $tempArray = [];

    foreach ($d as $data) {
        $value = explode("--", $d);
        $value = $value[1]; // Take the chain "12345.txt"
        $value = explode(".", $value);
        $value = $value[0]; // Take the chain "12345"
        $value = intval($value); // convert into integer

        array_push($tempArray, $value);
    }

    sort($value);
?>

Your best choice is to use uasort .

>>> $data
=> [
   3945 => "6358--338940.txt",
   3946 => "6357--348639.txt",
   3947 => "6356--348265.txt",
   3948 => "6354--345445.txt",
   3949 => "6354--340195.txt"
]
>>> uasort($data, function ($a, $b) { 
...   $pttrn = '#^[0-9]*--|\.txt$#';
...   $ka = preg_replace($pttrn, '', $a);
...   $kb = preg_replace($pttrn, '', $b);
...   return $ka > $kb;
... })
>>> $data 
=> [
   3945 => "6358--338940.txt",
   3949 => "6354--340195.txt",
   3948 => "6354--345445.txt",
   3947 => "6356--348265.txt",
   3946 => "6357--348639.txt"
 ]

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