6

I am trying to sort by a column(s) in the following data structure that I have built like this:

 $counter = 1;
 $entity_list = array();

 foreach($result as $rec){
   $entity_list[$counter]['student_first_name'] = $rec->firstname;
   $entity_list[$counter]['student_last_name'] = $rec->lastname;
   $entity_list[$counter]['course_name'] = $rec->fullname;
   .
   .
   $counter++;
 }//end foreach

This is a var_dump of the $entity_list data structure.

array (size=150)     
  1 => 
  array (size=3)
    'student_first_name' => string 'Jane' (length=6)
    'student_last_name' => string 'Smith' (length=7)
    'course_name' => string 'Algebra 1A-MOD' (length=14)

  2 => 
  array (size=3)
    'student_first_name' => string 'Fred' (length=6)
    'student_last_name' => string 'Jones' (length=7)
    'course_name' => string 'Algebra 1A-MOD' (length=14)
   .
   .
   .

How do I use asort() or ksort() on this structure? I think i should be using ksort(), as it works on a key. I have tried ksort($entity_list,'student_last_name'), or asort($entity_list,'current_grade') for example.

Thank you.

2
  • looks like it came from a db, use the db's sorting options. Commented Nov 5, 2012 at 19:07
  • I should have noted that i am creating calculated fields from the DB, of which I need to sort by.... Commented Nov 5, 2012 at 19:44

8 Answers 8

8

You can use uasort

uasort($entity_list, 'mySort');

function mySort($a, $b) {
    return ($a['student_last_name'] <==> $b['student_last_name']);
}

But if your data come from a DB, it would be a lot easier and lighter to ORDER BY.

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use the spaceship operator in PHP7 or newer. Improves readability by a lot.
I'm familiar with the spaceship operator, I didn't know about <==>¿
4

Easiest way is to use a callback with uasort like so

Lets say I'm sorting an array of trades by a column called timestamp...

uasort($trades, function ($a, $b) { 
    return ( $a['timestamp'] > $b['timestamp'] ? 1 : -1 ); 
});

Comments

2

You can use uasort() for that, like this:

function cmp($a, $b) {
    $sortby = 'student_last_name'; //define here the field by which you want to sort
    return strcmp($a[$sortby] , $b[$sortby]);
}

uasort($array, 'cmp');

Comments

2
function mySort($a, $b) {
    if($a['student_last_name'] == $b['student_last_name']) {
        return 0;
    }
    return ($a['student_last_name'] < $b['student_last_name']) ? -1 : 1; }

No, no, noo!!! That's ugly.

function mySort($a, $b) {
    return $a['student_last_name'] - $b['student_last_name'];
}

Comments

1

If you are on PHP 7.4 or higher you can use the spaceship operator in an arrow function:

uasort($entity_list, fn ($a, $b) => $a['student_last_name'] <=> $b['student_last_name']);

Comments

0

If you can use MySQL do this with it. Or try array_multisort() like this:

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);

Comments

0

From what I know or have tested on, php 5+ is more stable for this function.

function orderBy($data=NULL,$field='order',$order='asc') 
    {
        if (!is_null($data)) {
            define('FIELD_TARGET',$field); define('ORDER_DIRECTION',$order);
            usort($data,function($a, $b) { 
                if (ORDER_DIRECTION == 'desc') { return ($b[''.FIELD_TARGET.''] - $a[''.FIELD_TARGET.'']); } 
                else { return ($a[''.FIELD_TARGET.''] - $b[''.FIELD_TARGET.'']); }
            }); return $data;
        }
    }

Comments

0

It may be usable for common situations.

PHP 5.4 >

function arraySortByCol(&$arr, $col, $dir = 'asc')
{
    usort($arr,function($a,$b) use ($col, $dir) {
        return ($dir === 'asc')
            ? strcmp($a[$col], $b[$col])
            : strcmp($b[$col], $a[$col]);
    });
}

PHP 7 >

function arraySortByCol(&$arr, $col, $dir = 'asc')
{
    usort($arr,function($a,$b) use ($col, $dir) {
        return ($dir === 'asc')
            ? $a[$col] <=> $b[$col]
            : $b[$col] <=> $a[$col];
    });
}

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.