-2

I have this array:

$po = array ( 
5 => '8', 
6 => '10', 
7 => '12', 
8 => '41', 
12 => '42', 
9 => '43', 
10 => '44', 
11 => '45', 
1 => 'L', 
0 => 'M', 
4 => 'S', 
2 => 'XL', 
3 => 'XXL', 
13 => 'XXS'
)

I need to have it sorted this way:

  1. All numeric first asc
  2. All leters by this order: $order = ['XXS','XS','S','M','L','XL','XXL'];

So far I have this code taken from internet examples:

$sort_first  = array('XXS','XS','S','M','L','XL','XXL');
usort($poval, function ($a, $b) use ($sort_first) {
$posA = array_search($a, $sort_first);
$posB = array_search($b, $sort_first);
return $posA - $posB;
});

but numeric values are not OK.. This is export after reordering:

$po = array ( 
0 => '8', 
1 => '45', 
2 => 'XXS', 
3 => '43', 
4 => '44', 
5 => '42', 
6 => '10', 
7 => '12', 
8 => '41', 
9 => 'S', 
10 => 'M', 
11 => 'L', 
12 => 'XL', 
13 => 'XXL'
)

How can I do that? Thanks for your time

Europeuser
  • 843
  • 1
  • 6
  • 21
  • Please post the code you already have along with any errors you might get. A valid PHP array would also help – brombeer May 10 '21 at 08:09
  • A tip for the future: share a dump generated by `var_export`, because it allows us to simply copy and paste it into an editor to recreate your variable. – El_Vanja May 10 '21 at 08:37
  • #El_Vanja thank you for your tip, I made corrections you suggested – Europeuser May 10 '21 at 08:55

2 Answers2

0

If I understand you correctly, you can itterate your array and split it up into two seperate arrays - one for numeric and one for non numeric values - then merge them back together, but I can't tell you if this is valid php syntax.

june4
  • 15
  • 4
0

You can create a custom sort using usort.

usort($values, function($a, $b){
    // Your custom logic here
    if( ctype_digit($a) && !ctype_digit($b) ){
         return -1;
    }
    if( !ctype_digit($a) && ctype_digit($b) ){
         return 1;
    }
    if( ctype_digit($a) && ctype_digit($b) ){
         return $a <=> $b;
    }

    // now you can do something here to sort if $a and $b are both non numeric.
});

(Untested code, I could've mixed up the plus and minus)

Martijn
  • 14,522
  • 4
  • 29
  • 61