What I want to do is create a Comparable
class, similar to IComparable
in .NET, such that you can instantiate it like so:
$cmp = new MultiArrayCompare(2);
And then you can sort an array via:
usort($myArray, $cmp);
And it will sort an array of arrays on the 2nd index. To do that, I imagine usort
would try to call $cmp
like a function, so I'd have to override that behaviour somehow. It doesn't look like __call
does what I want (thought for a minute it was like Python's __call__
).
If this isn't possible... is there another nice way to create a general solution to this problem? Where you can create a user-defined sorting function but give pass it some value ("2" in this case)?
Using __invoke
I was able to create these classes:
abstract class Comparable {
abstract function Compare($a, $b);
function __invoke($a, $b) {
return $this->Compare($a, $b);
}
}
class ArrayCompare extends Comparable {
private $key;
function __construct($key) {
$this->key = $key;
}
function Compare($a, $b) {
if($a[$this->key] == $b[$this->key]) return 0;
return $a[$this->key] < $b[$this->key] ? -1 : 1;
}
}
class ArrayCaseCompare extends Comparable {
private $key;
function __construct($key) {
$this->key = $key;
}
function Compare($a, $b) {
return strcasecmp($a[$this->key], $b[$this->key]);
}
}
Which I can use to sort an array of arrays:
$arr = array(
array(1,2,3),
array(2,3,4),
array(3,2,4),
)
usort($arr,new ArrayCompare(1));