0

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

gr68
  • 420
  • 1
  • 10
  • 25
  • 1
    Using [usort()](http://www.php.net/manual/en/function.usort.php) with a custom callback – Mark Baker Nov 25 '14 at 09:19
  • thanks, can you explain me the meaning of "with a custom callback" ? – gr68 Nov 25 '14 at 09:21
  • the documentation can. a google search can. – Karoly Horvath Nov 25 '14 at 09:23
  • I read usort doc but I can't find a way, If I am here it means docs didn't help. – gr68 Nov 25 '14 at 09:25
  • 1
    no, it means you're lazy. – Karoly Horvath Nov 25 '14 at 09:25
  • Start by reading the doc page that I linked to for usort, and looking at the examples there.... then write a function that splits your filename string and compares the numeric part that you want to sort on... if you're still having problems then, edit your code into your question – Mark Baker Nov 25 '14 at 09:25
  • Mark, I was thinking there was a faster way to do that without splitting the filename and creating a new array, for this reason I was asking here.From your reply I understand there is no way, ok I will try. – gr68 Nov 25 '14 at 09:28
  • Could it be a duplicated of this topic?: http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – José Antonio Postigo Nov 25 '14 at 09:28
  • You're not creating a new array anywhere, simply splitting the filename in the sort callback – Mark Baker Nov 25 '14 at 11:35

2 Answers2

0

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);
?>
Anwar
  • 4,162
  • 4
  • 41
  • 62
0

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"
 ]
markcial
  • 9,041
  • 4
  • 31
  • 41