0

I have following array

    Array(
           [0]= Array
               ( 
              [name]=>room
             other paramters

            )
       [1]=Array (
         [name]=>abc
        and so on

    )

   )

I want to sort by name

i tried to use usort. but i am not able to get proper results

usort($array,'sort_by_name');
function sort_by_name($a,$b) {
 return $a- $b;
}

Any idea?

Thanks

3
  • usort() is probably not what you need, and without showing the rest of the code we can only assume you're not using it correctly. Try ksort(). Commented Jan 28, 2015 at 18:30
  • @slime ksort would sort by the key, not the value. As in the 0 and 1. @OP usort is correct and in your compare function just use something like return strcasecmp($a['name'], $b['name']); in your compare function. php already has a string comparison function that returns the proper values, you just need to reference the key. Commented Jan 28, 2015 at 18:33
  • function sort_by_name($a,$b) { return strcmp($a['name'], $b['name']); } perhaps? Commented Jan 28, 2015 at 18:39

2 Answers 2

1

You should use array_multisort. For your particular example, where $array is the initial array:

$names = array();
foreach ($array as $key => $row)
{
    $names[$key] = $row['name'];
}
array_multisort($names, SORT_ASC, $array);
Sign up to request clarification or add additional context in comments.

Comments

0

This method allows you to sort data in a direction, specify a field, and say if the field is a date.

private function multiSort($data, $sortDirection, $field, $isDate) {
if (empty($data) || !is_array($data) || count($data) < 2) {
    return $data;
}

$parts = explode("/", $field);
foreach ($data as $key => $row) {
    $temp = &$row;
    foreach ($parts as $key2) {
        $temp = &$temp[$key2];
    }
    $orderByDate[$key] = ($isDate ? strtotime($temp) : $temp);
}
unset($temp);
unset($parts);

if ($sortDirection == "SORT_DESC") {
    array_multisort($orderByDate, SORT_DESC, $data);
} else {
    array_multisort($orderByDate, SORT_ASC, $data);
}
unset($orderByDate);
return $data;
}

This blog post should be helpful: Multisort by key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.