-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!

4

1 回答 1

2

你所需要的只是排序

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

        return $aBytes - $bBytes;
   });

convertInBytes 不存在,您当然需要对其进行编码;)

这是一个向您展示如何以字节为单位转换的链接:PHP convert KB MB GB TB etc to Bytes

于 2013-11-12T19:33:35.803 回答