Saturday, 15 June 2013

PHP - Array Sorting -



PHP - Array Sorting -

so wanting sort array depending on user selects, have managed working (with little help guys) , trying clean code. i've got

//global sorting functions (for rows columns) //function sort or downwards function cmpdwn($a, $b) { homecoming strcasecmp($a["name"], $b["name"]); } function cmpup($a, $b, $c) { homecoming strcasecmp($b[$c], $a[$c]); } //name ordering function --------------------------------- function nameorder($data) { //if sorts assending if downwards decending if ($_post['sortby'] == "namedown") { uasort($data, "cmpdwn"); } else { uasort($data, "cmpup"); } $nameorder = array(); $count = 0; while (list($key, $value) = each($data)) { $nameorder[$count] = $key; $count++; } homecoming $nameorder; }

this creates array order print info in name order, repeating email , others. wanted re-use "cmp" function putting more $a , $b (i.e. $c = "name" can set in "email" or ever // cmpup example). little know function declaring argument uasort , don't send variables it. there way or case of re writing function repeatedly

thanks , big love

try create object

class mycomparator { private $key; function __construct($key) { $this->key = $key; } function compare($a, $b) { homecoming strcasecmp($b[$this->key], $a[$this->key]); } public function setkey($key) { $this->key = $key; } }

and utilize it

$compararor = new mycomparator("name"); usort($data, array($compararor, "compare"));

or in php >= 5.3.0. can utilize __invoke() method

class mycomparator { private $key; function __construct($key) { $this->key = $key; } function __invoke($a, $b) { homecoming strcasecmp($b[$this->key], $a[$this->key]); } public function setkey($key) { $this->key = $key; } }

and simple phone call with

$compararor = new mycomparator("name"); usort($data, $compararor);

php arrays sorting

No comments:

Post a Comment