I've an array of array.
I'm trying this code to sort main array based of a field of every single element of the main array.
$field = $this->sorting;
usort($this->out_table["rows"], function($a, $b) use ($field) {
return strnatcmp($a[$field], $b[$field]);
});
But I got this
Parse error: syntax error, unexpected T_FUNCTION
Referred to the second line, the one which starts with 'usort'
What am I missing?
My php version is
PHP 5.2.4-2ubuntu5.27 with Suhosin-Patch 0.9.6.2 (cli) (built: Mar 11 2013 14:14:48)
PHP 5.2 doesn't support anonymous functions. Anonymous functions are instances of the Closure
class, which as the docs say, wasn't introduced until 5.3... PS: _upgrade your PHP version, 5.2 was EOL'ed ages ago.
For now, though, you're best off writing your own class, pass the $field
value to that class' instance and use the array-style callable argument:
class Sorter
{
protected $field = null;
public function __construct($field)
{
$this->field = $field;
}
public function sortCallback($a, $b)
{
return strnatcmp($a[$this->field], $b[$this->field]);
}
}
$sorter = new Sorter($field);
usort($this->out_table["rows"], array($sorter, 'sortCallback'));
Which is basically what a Closure
instance does, the anonymous function business is syntactic sugar in this case. The advantage of a class like this is that you could add some more sort-callbacks to it, and keep it handy as a sort of utility class with a sortAscending
and sortDescending
callback method, for example. Along with options you can set on the instance that make the sorter use strict (type and value) comparison where it's needed....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With