Skip to content

Instantly share code, notes, and snippets.

@andrew-svirin
Created November 13, 2019 09:39
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 andrew-svirin/e46ec5fe3e0d71f5ad7497e5050b872a to your computer and use it in GitHub Desktop.
Save andrew-svirin/e46ec5fe3e0d71f5ad7497e5050b872a to your computer and use it in GitHub Desktop.
<?php
/**
* Sorting class for array of associative arrays.
*
* Allows sort array by children array field value.
*
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*
* @example
* ```php
* uasort($data, [
* new ArrayAssocSort($field),
* 'compareAscending',
* ]);
* ```
*/
class AssocArrayArraysSort {
/**
* Field name of children array for that will be sorting.
*
* @var string
*/
private $field;
/**
* ArrayAssocSort constructor.
*
* @param string $field
* Field name.
*/
public function __construct($field) {
$this->field = $field;
}
/**
* Compares elements ASC.
*
* @param array $one
* The first element to compare.
* @param array $two
* The second element to compare.
*
* @return int
* The compared result (-1|0|1).
*/
public function compareAscending(array $one, array $two) {
if (isset($one[$this->field]) && isset($two[$this->field])) {
return strnatcmp($one[$this->field], $two[$this->field]);
}
return 0;
}
/**
* Compares elements DESC.
*
* @param array $one
* The first element to compare.
* @param array $two
* The second element to compare.
*
* @return int
* The compared result (-1|0|1).
*/
public function compareDescending(array $one, array $two) {
if (isset($one[$this->field]) && isset($two[$this->field])) {
return strnatcmp($two[$this->field], $one[$this->field]);
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment