-3

you might be thinking that this same question has been posted a million times, but I have one special exception that makes this a little bit different.

so I have an array that looks like this:

$array = array(
    array('name' => 'foo', 'capacity' => "128MB"),
    array('name' => 'foo2', 'capacity' => "256MB"),
    array('name' => 'foo3', 'capacity' => "512MB"),
    array('name' => 'foo4', 'capacity' => "16GB"),
    ...
);

As you can see I have data values under capacity with MB and GB so the result of that looks like this:

foo = 128MB
foo4 = 16GB
foo2 = 256MB
foo3 = 512MB

I need to sort by the capacities in a logical way, that separates MB and GB values puts MB first and also looks 3 digits into the number to sort so I don't get this type of sorting:

   1 = 100
   2 =  12
   3 = 140

Unfortunately converting all capacity values to MB and then just displaying as GB when needed is not an option.

I'm wondering what all you smart people have in mind? Any help would be greatly appreciated!

Thanks!

Spittal
  • 779
  • 2
  • 12
  • 23
  • put all capacities in kilobytes sort on that and convent on display. –  Nov 12 '13 at 19:31
  • This is incredibly customized sorting, what have you tried and where are you stuck? I don't see any `for()` loops in the body. Questions like this usually get downvoted quickly. – MonkeyZeus Nov 12 '13 at 19:31
  • @MonkeyZeus thanks for the reply, I haven't written much code around this yet, I was more in the "thinking of how" to do it stage. I just thought Stack might have a few better suggestions than what I had in my head. – Spittal Nov 12 '13 at 19:38

1 Answers1

2

All you need is usort

   usort($array, function($a, $b){
        $aBytes = convertInBytes($a['capacity']);
        $bBytes = convertInBytes($b['capacity']);

        return $aBytes - $bBytes;
   });

convertInBytes does not exists, you need to code it of course ;)

Here is a link to show you how to convert in bytes : PHP convert KB MB GB TB etc to Bytes

Community
  • 1
  • 1
Raphaël Malié
  • 3,912
  • 21
  • 37