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.

3
  • which output you want? it will be more clear Commented May 8, 2017 at 12:34
  • 3
    Duplicate of this stackoverflow.com/questions/3232965/… Commented May 8, 2017 at 12:34
  • if this comes from a database you may want to change your query Commented May 8, 2017 at 12:39

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

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.