Created
November 13, 2019 09:39
-
-
Save andrew-svirin/e46ec5fe3e0d71f5ad7497e5050b872a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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