user1190646
user1190646

Reputation:

php - how to sort an array with values like "+1", "-20"

I have a PHP script with an array like this:

array (

"+15" => 5,
"-5" => 20,
"+2" => 2,
"-1" => 9

)

The keys are all unique (the +15 etc). I want to sort by the keys so this:

foreach($array as $k => $v ) {

echo $k . ' has a count of ' . $v;

}

any ideas on sorting by the keys with + and -'s. I can't get that working correctly

Upvotes: 0

Views: 314

Answers (2)

Cory James
Cory James

Reputation: 144

Would natsort() work?

From php.net:

<?
    $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

    asort($array1);
    echo "Standard sorting\n";
    print_r($array1);

    natsort($array2);
    echo "\nNatural order sorting\n";
    print_r($array2);
?>

Output:

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Upvotes: 0

xdazz
xdazz

Reputation: 160853

You could just use ksort, (your keys are all numeric strings, they will be treated as integers.)

ksort($array);
var_dump($array);

Result:

array(4) {
  [-5]=>
  int(20)
  [-1]=>
  int(9)
  ["+2"]=>
  int(2)
  ["+15"]=>
  int(5)
}

Upvotes: 2

Related Questions