0

Can someone help me i need to sort this array:

$report_fields['client_id'] = $row['client_id'];
$report_fields['name'] = $row['name'];
$report_fields['is_authorized'] = $row['is_authorized'];
$report_fields['date_created'] = $row['date_created'];
$report_fields['service_id'] = $row['service_id'];
$report_fields['type_id'] = $row['type_id'];
$report_fields['report_name'] = $report_types[$row['type_id']]['type'];


$report_groups[$row['ref_no']][$row['id']] = $report_fields;

I have tried usort like so:

usort($report_groups[$row['ref_no']],'cmp');

function cmp($a,$b) { 
   $a_stm = strtotime($a["date_created"]);
   $b_stm = strtotime($b["date_created"]);

   if ($a_stm == $b_stm) {
    return 0;
    }

   return ($a_stm < $b_stm) ? -1 : 1;

}

But the result returned is incorrect.

2
  • Is there any error message with E_ALL? Commented May 15, 2011 at 20:49
  • We might recommend array_multisort() but if your ref_no values are numeric, you'll lose them. This question is missing its minimal reproducible example. Implementing usort() is going to be a little more clumsy because you have dynamic id values as the second level keys -- so you'd need two function calls on each iteration. Commented Feb 2 at 10:27

1 Answer 1

1

array_multisort is what you want to use.

Here's an example

<?php

$sort = array(
    array(),
    array()
);

foreach ($results as $k=>$result) {
    $sort[0][$k] = $result['sort_field_one'];
    $sort[1][$k] = $result['sort_field_two'];   
}


# sort using $sort[0] DESC and $sort[1] ASC
array_multisort($sort[0], SORT_DESC, $sort[1], SORT_DESC, $results);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.