1

I have an array as follows:

//0-based index, 2 dimensions
$data = array(
    array(
        'name'=>'EJA210E',
        'id'=>439,
        'region_id'=>17,
        .. other attributes ..
    ),
    array(
        'name'=>'EJA210E',
        'id'=>440,
        'region_id'=>3,
    ),
    array(
        'name'=>'EJA210E',
        'id'=>439,
        'region_id'=>15,
    ),
    .. etc..
);

What would be sort, first by name, then by id, then by region_id? Sorting by any one of these is no problem; I would simply loop through and get the name attribute, then re-order, however doing this three times I do not understand how to do.

Oliver Williams
  • 5,966
  • 7
  • 36
  • 78

2 Answers2

2

You can try array_multisort by passing different ordering columns as shown below :

$data = array(
    array(
        'name'=>'EJA210E',
        'id'=>439,
        'region_id'=>17,        
    ),
    array(
        'name'=>'EJA210E',
        'id'=>440,
        'region_id'=>3,
    ),
    array(
        'name'=>'AJA210E',
        'id'=>438,
        'region_id'=>15,
    )  
);
// Obtain a list of columns
foreach ($data as $key => $row) {
    $name[$key]  = $row['name'];
    $id[$key] = $row['id'];
    $region[$key] = $row['region_id'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($name, SORT_DESC, $id, SORT_DESC,$region, SORT_DESC, $data);
Nishesh Pratap Singh
  • 2,131
  • 2
  • 13
  • 20
0

You could use usort() with a custom sorting function. Here's an example:

function cmp($a, $b)
{
   if ($a['name'] == $b['name']) {
      if ($a['id'] == $b['id']) { 
         if ($a['region_id'] == $b['region_id']) {
            return 0;
         }
         return $a['region_id'] < $b['region_id'] ? -1 : 1;
      }
      return $a['id'] < $b['id'] ? -1 : 1;
   }
   return ($a['name'] < $b['name']) ? -1 : 1;   
}

usort($data, 'cmp');
Ray
  • 40,256
  • 21
  • 101
  • 138