July 29, 2009 | PHP Scripting | Leave a comment
I don’t know why but I have an infatuation with little utility functions. Its pretty stupid, but it keeps me entertained and provides me with a cheap blog post
That and I’ve noticed it trending A LOT in my search keywords lately, so I figure I should post some updated and easier to use code.
A few years ago I posted on Sorting Multidimensional Arrays by Key. The solution had php4 and php5 version and they were class based. Kind of awkward to use. They were originally dumped in a framework and accessed statically. After much tweaking and moving it from project to project it is down to a single function that also sorts arrays of objects my member variables.
- <?php
-
- @example
-
- @param
- @param
- @param
- @return
- function array_sort_by_key($data,$sort_key,$ascending=true) {
- $order = $ascending ? '$a,$b' : '$b,$a';
- if(is_object(current($data))) { $callback = create_function($order,'return strnatcasecmp($a->'.$sort_key.',$b->'.$sort_key.');'); }
- else { $callback = create_function($order,'return strnatcasecmp($a["'.$sort_key.'"],$b["'.$sort_key.'"]);'); }
- uasort($data,$callback);
- return $data;
- }
- ?>
Less code. Easier to use. Single code base for php4 and php5. And once php 5.3 becomes more ubiquitous I can rewrite it again to use lambda functions