Skip to content

Instantly share code, notes, and snippets.

@insideone
Created May 15, 2016 13:27
Show Gist options
  • Save insideone/18cb3660bcc43e3b380f3f60014e0426 to your computer and use it in GitHub Desktop.
Save insideone/18cb3660bcc43e3b380f3f60014e0426 to your computer and use it in GitHub Desktop.
PHP: xsort
<?php
define('TABLE_SORT_ASC', 0);
define('TABLE_SORT_DESC', 1);
/**
* Сортирует массив по ключу который может лежать глубоко внутри
* @param array $data Массив который нужно отсортировать
* @param string $sortpath Путь к значению по которому должна вестись сортировка
*/
function xsort(&$data, $sortpath)
{
$path = '[\''.implode('\'][\'', explode('/', $sortpath)).'\']';
_xsort($path, $path, $path, TABLE_SORT_ASC);
usort($data, '_xsort');
}
/**
* Вспомогательная функция для xsort
* @param mixed $lv
* @param mixed $rv
* @param string $newPath
* @return bool Результат сравнения двух элементов массива
*/
function _xsort(&$lv, &$rv, $npath = null, $ndirect = TABLE_SORT_ASC)
{
static $path = null, $direct = null;
if ( $npath !== null )
{
$path = $npath;
$direct = $ndirect == 0 ? TABLE_SORT_ASC : $ndirect;
return;
}
eval('$lp = $lv'.$path.'; $rp = $rv'.$path.';');
return $direct * ($lp < $rp ? -1 : (($lp === $rp) ? 0 : 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment