longphant Posted February 21, 2012 Share Posted February 21, 2012 Hi, I have a function where I want to sort an an array of this type: 0 = {'fruit' => 'banana', 'color' => 'yellow', 'age' => '1', 'weight' => '2', 'brand' => 'dole', 'store' => shaws'} 1 = {'fruit' => 'apple', 'color' => 'red', 'age' => '3', 'weight' => '5', 'brand' => 'fuji', 'store' => 'foodmaster'} etc etc. I then want to array_multisort this array with different parameters. One way is to sort by fruit, then color, then brand. The second way by age, then store. //This is how I sort it for my first way //Let's call the array $rows function sort($rows) { foreach($rows as $key => $value) { $fruit[$key] = $value['fruit']; $color[$key] = $value['color']; $brand[$key] = $value['brand']; } array_multisort($fruit, SORT_ASC, $color, SORT_ASC, $brand, SORT_ASC $rows); } I want to try to reuse this function by passing in the keys that I want to sort with. Like doing sort($rows, array('fruit', 'color', 'brand')), then sort($rows, array('age', 'store')). Is this possible? Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 21, 2012 Share Posted February 21, 2012 Not pretty, but it works: //Class for custom sorting class customSort { private $sortArray = array(); function __construct($sortArray) { $this->sortArray = $sortArray; } function doSort__($a,$b) { foreach($this->sortArray as $key) { if ($a[$key] != $b[$key]) { return (($a[$key] > $b[$key]) ? 1 : -1); } } return 0; } } ## USAGE ## //Define array sof keys to sort by - in order $sortKeys = array('color', 'age', 'brand'); //Perform the sorting usort($inputArray, array(new customSort($sortKeys), "doSort__")); //Original array is now sorted Quote Link to comment Share on other sites More sharing options...
longphant Posted February 21, 2012 Author Share Posted February 21, 2012 This works. Thank you very much! Quote Link to comment Share on other sites More sharing options...
kicken Posted February 21, 2012 Share Posted February 21, 2012 If you have 5.3 or better and can use closures: function getCompareFn($keys){ return function($a, $b) use ($keys) { foreach ($keys as $k){ if ($a[$k] < $b[$k]){ return -1; } else if ($a[$k] > $b[$k]){ return 1; } } return 0; }; } $arr=array( array('name' => 'a', 'group' => 'a', 'order' => 2), array('name' => 'b', 'group' => 'a', 'order' => 1), array('name' => 'c', 'group' => 'b', 'order' => 5), array('name' => 'd', 'group' => 'c', 'order' => 3), array('name' => 'e', 'group' => 'b', 'order' => 4), array('name' => 'f', 'group' => 'c', 'order' => 6) ); usort($arr, getCompareFn(array('group', 'order'))); print_r($arr); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.