tags:

views:

235

answers:

2

I have the following?

$array1 = array();

$array2 = array($Id, $Name, $Count);

array_push($array1, $array2);

I want to sort array1 on the $count?

sort() and ksort() don't do what i require?

Any ideas?

Thanks

Edit:

I am inputing an Id number, name text and number of times the name occurs, so I want to to have the name with the highest count at the top of the array!!

+3  A: 

Use uasort() to sort with a callback function. Example:

function sort_callback($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }

    return ($a[2] < $b[2]) ? -1 : 1;
}

uasort($array1, 'sort_callback');
Sander Marechal
+1  A: 

I'm a bit confused by the way you've presented the question, but are you trying to do something like this?

function order_by($data, $field_name) {

    $code = "return strnatcmp(\$a['$field_name'], \$b['$field_name']);";
    usort($data, create_function('$a,$b', $code));
    return $data;

}

So, for example:

$array1 = array();
$array1[] = array('Id' => 1, 'Name' => 'YT', 'Count' => 30);
$array1[] = array('Id' => 2, 'Name' => 'Da5id', 'Count' => 56);
$array1[] = array('Id' => 3, 'Name' => 'Fido', 'Count' => 12);
$array1[] = array('Id' => 4, 'Name' => 'Hiro', 'Count' => 45);

echo "<pre>";
print_r($array1);
echo "</pre>";

$array2 = order_by($array1, 'Count');

echo "<pre>";
print_r($array2);
echo "</pre>";
da5id