[Resolved] Sorting an array.

SpaceshipSpaceship
Watch

Barrucadu

Established Member
Impact
64
Sorting an array.

I've got an array in this format:
PHP:
$array['text'] = number;

How would I sort by the numbers, not the text? I've tried:
PHP:
$tmp = array();
foreach($array as $key => $var){
     $tmp[$var] = $key;
}
$array = ksort($tmp);

But it dosn't work.
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
AfternicAfternic
The following demonstrated how to do it. I have used print_r to show the order before and after the sorting.

PHP:
<?php
$array = array('one'=>'1','three'=>'3','seven'=>'7','two'=>'2');
print_r($array);
asort($array);
print_r($array);
?>

The method of using ksort that you was using will not work in ordering the values in the array as ksort is used for ordering the key (where you have the text) ksort
 
Last edited:
0
•••
Nevermind, stupid mistake.
 
Last edited:
0
•••
yeah I see what you have done. The asort returns 1 because it was successful in sorting the array.
 
0
•••
Still not working
PHP:
echo "<pre>UNSORTED:\r\n";
print_r($thing);
echo "\r\nSORTED:\r\n";
asort($thing, SORT_NUMERIC);
print_r($thing);
echo "</pre>";

Outputs:
Code:
<pre>UNSORTED:
Array
(
    [yahoo] => 4
    [opera 9.22] => 9
    [internet explorer 7.0] => 12
    [internet explorer 6.0] => 29
)

SORTED:
Array
(
    [yahoo] => 4
    [opera 9.22] => 9
    [internet explorer 7.0] => 12
    [internet explorer 6.0] => 29
)
</pre>
 
0
•••
can you post the full code and the expected output.

Looking at what you just posted I might be misunderstanding what you want. The array is already sorted by the values.
 
0
•••
Mikor said:
Still not working
PHP:
echo "<pre>UNSORTED:\r\n";
print_r($thing);
echo "\r\nSORTED:\r\n";
asort($thing, SORT_NUMERIC);
print_r($thing);
echo "</pre>";

Outputs:
Code:
<pre>UNSORTED:
Array
(
    [yahoo] => 4
    [opera 9.22] => 9
    [internet explorer 7.0] => 12
    [internet explorer 6.0] => 29
)

SORTED:
Array
(
    [yahoo] => 4
    [opera 9.22] => 9
    [internet explorer 7.0] => 12
    [internet explorer 6.0] => 29
)
</pre>

The array looks sorted to me, although it already was sorted before the asort. How did expect it to look?
 
0
•••
Got it working now, I needed to use arsort. (The fact that it was sorted before was a coincidence, it probably won't always be)
 
0
•••
ahh so you wanted the numbers in reverse order i.e. highest first.
 
0
•••
Appraise.net

We're social

Escrow.com
Spaceship
Rexus Domain
CryptoExchange.com
Domain Recover
CatchDoms
DomDB
NameFit
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back