Jump to content

Sorting associative arrays...


Axet

Recommended Posts

Alright, well, I have an associative array which assigns arrays of 4 values to strings (see the example below):

 

Array ( [value1] => Array ( [0] => 65 [1] => 2 [2] => 75 [3] => -10 ) [value2] => Array ( [0] => 65 [1] => 2 [2] => 0 [3] => 65 ) [value3] => Array ( [0] => 15 [1] => 2 [2] => 5 [3] => 10 ) )

 

Up to now, I've been using ksort on the big array and it sorted it by the "value1", "value2", etc., alphabetically. Now, however, I want it sorted numerically by the 4th value of each array inside the big array (the -10, 65, and 10 in the above example).

 

How would I go about doing this?

 

Thanks in advance for any help ;D

Link to comment
https://forums.phpfreaks.com/topic/64785-sorting-associative-arrays/
Share on other sites

i prefer a custom sort function in these cases

<?php
$data = array ( 
    'value1' => array ( 0 => 65, 1 => 2, 2 => 75, 3 => -10 ), 
    'value2' => array ( 0 => 65, 1 => 2, 2 => 0,  3 => 65 ), 
    'value3' => array ( 0 => 15, 1 => 2, 2 => 5,  3 => 10 ) 
    );
    
uasort($data, 'mysort');

echo '<pre>', print_r($data, true), '</pre>';      // check result

function mysort($a, $b)
{
    if ($a[3] == $b[3]) return 0;
    return $a[3] < $b[3] ? -1 : 1;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.