0

How do I sort the following data in the order I want it?

The array:

array(4)
{ 
[21]=> string(7) "2-2.pdf" 
[22]=> string(7) "2-3.pdf"
[23]=> string(7) "2-4.pdf" 
[24]=> string(5) "2.pdf" 
} 

I want this sort:

2.pdf
2-2.pdf
2-3.pdf
2-4.pdf
3
  • 1
    And what have you tried to achieve that? Eg, you can define your own comparison function via usort() Commented Oct 12, 2014 at 10:43
  • But I dont know what I should write in the cmp function. Commented Oct 12, 2014 at 10:52
  • This might help you. <?php $check_array = array('2-2.pdf','2.pdf','2-3.pdf','2-4.pdf'); function cmp($a, $b) { return strcmp($a, $b); } usort($check_array, "cmp"); echo "<pre/>"; print_r($check_array); ?> Just the 2.pdf is the last element of final result Commented Oct 12, 2014 at 11:08

2 Answers 2

2

Yes you could use usort in this case:

$array = [21=> "2-2.pdf", 22=> "2-3.pdf", 23=> "2-4.pdf",24=> "2.pdf", ];
usort($array, function($a, $b){
    $a = str_replace('-', '', $a);
    $b = str_replace('-', '', $b);
    return $a - $b;
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do like this:

<?php
   $check_array = array('2-2.pdf','2.pdf','2-3.pdf','2-4.pdf');

   function cmp($a, $b)
   {
       $a = preg_replace('/-/','',$a);
       $b = preg_replace('/-/','',$b);
       return strcmp($a, $b);
   }


   usort($check_array, "cmp");


   echo "<pre/>"; print_r($check_array);
 ?>

And the result is:

<?php Array ( [0] => 2.pdf [1] => 2-2.pdf [2] => 2-3.pdf [3] => 2-4.pdf ) ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.