Skip to content

Instantly share code, notes, and snippets.

@ThomasWeinert
Created July 17, 2013 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasWeinert/6020140 to your computer and use it in GitHub Desktop.
Save ThomasWeinert/6020140 to your computer and use it in GitHub Desktop.
<?php
$data = array(
array('volume' => 67, 'edition' => 2),
array('volume' => 86, 'edition' => 1),
array('volume' => 85, 'edition' => 6),
array('volume' => 98, 'edition' => 2),
array('volume' => 86, 'edition' => 6),
array('volume' => 67, 'edition' => 7)
);
var_dump($data);
$sorted = $data;
usort(
$sorted,
function($i1, $i2) {
$result = strnatcasecmp($i1['volume'], $i2['volume']);
if (0 == $result) {
$result = strnatcasecmp($i1['edition'], $i2['edition']);
}
return $result;
}
);
var_dump($sorted);
class CompareColumns {
private $_columns = array();
private $_callback = 'strnatcasecmp';
public function __construct(array $columns, Callable $callback = NULL) {
$this->_columns = $columns;
if (isset($callback)) {
$this->_callback = $callback;
}
}
public function __invoke() {
list($one, $two) = func_get_args();
$result = 0;
foreach ($this->_columns as $column) {
$result = call_user_func($this->_callback, $one[$column], $two[$column]);
if ($result !== 0) {
break;
}
}
return $result;
}
}
usort(
$sorted,
new CompareColumns(array('volume', 'edition'))
);
var_dump($sorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment