sorting a column in a PHP array
Asked Answered
C

8

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.

Calvincalvina answered 5/11, 2012 at 19:4 Comment(2)
looks like it came from a db, use the db's sorting options.Foresail
I should have noted that i am creating calculated fields from the DB, of which I need to sort by....Calvincalvina
S
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.

Salzhauer answered 5/11, 2012 at 19:11 Comment(1)
You can also use the spaceship operator in PHP7 or newer. Improves readability by a lot.Interspace
J
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 ); 
});
Jacquerie answered 14/3, 2014 at 0:10 Comment(0)
M
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');
Muggy answered 5/11, 2012 at 19:13 Comment(0)
T
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'];
}
Teredo answered 25/3, 2014 at 11:51 Comment(0)
S
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']);
Selimah answered 24/4, 2022 at 10:32 Comment(0)
S
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);
Striker answered 5/11, 2012 at 19:14 Comment(0)
D
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;
        }
    }
Drawee answered 4/8, 2015 at 11:20 Comment(0)
K
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];
    });
}
Kauffman answered 20/2, 2019 at 14:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.