PHP array sorting?

Do I have the following?

$array1 = array();

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

array_push($array1, $array2);

      

I want to sort array1 by $ account?

sort()

and ksort()

don't do what I need?

Any ideas?

thanks

Edit:

I enter the Id number, the text of the name, and the number of times that name occurs, so I want the highest-counted name at the top of the array to be

0


a source to share


2 answers


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');

      

+2


a source


I'm a little confused about how you presented the question, but are you trying to do something similar?

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>";

      

+1


a source







All Articles