method sortBy documentation in bbn\X

Sorts the items of an indexed array based on a given $key.

Example

$v = [ ['age'=>10, 'name'=>'thomas'], ['age'=>22, 'name'=>'John'], ['age'=>37, 'name'=>'Michael'] ]; X::sortBy($v,'name','desc'); X::hdump($v); X::sortBy($v,'name','asc'); X::hdump($v); X::sortBy($v,'age','asc'); X::hdump($v); X::sortBy($v,'age','desc'); X::hdump($v); function(array &$ar, $key, $dir = '') { $blackOrder = [ false, null, 0, '', [] ]; $args = \func_get_args(); array_shift($args); if (is_array($key)) { $args = $key; if (X::isAssoc($args)) { $args = [$args]; } } elseif (\is_string($key)) { $args = [[ 'key' => $key, 'dir' => $dir ]]; } usort( $ar, function ($a, $b) use ($args, $blackOrder) { foreach ($args as $arg) { if (!is_array($arg)) { throw new Exception(X::_("the order must be made of arrays, not %s", (string)$arg)); } $key = $arg['key'] ?? $arg['field'] ?? null; if (!$key) { throw new Exception(X::_("the order must have a field or key and a dir key")); } $dir = strtolower($arg['dir'] ?? 'asc'); if (!\is_array($key)) { $key = [$key]; } $v1 = self::pick($a, $key); $v2 = self::pick($b, $key); if (!$v1) { if ($v2) { $v1 = -1; $v2 = 1; } else { $v1 = array_search($v1, $blackOrder); $v2 = array_search($v2, $blackOrder); } } elseif (!$v2) { $v1 = 1; $v2 = -1; } elseif (is_array($v1)) { if (!is_array($v2)) { $v1 = 1; $v2 = -1; } else { $v1 = json_encode($v1); $v2 = json_encode($v2); } } elseif (is_array($v2)) { $v1 = -1; $v2 = 1; } elseif (is_object($v1)) { if (!is_object($v2)) { $v1 = 1; $v2 = -1; } else { $v1 = json_encode($v1); $v2 = json_encode($v2); } } elseif (is_object($v2)) { $v1 = -1; $v2 = 1; } $a1 = $dir === 'desc' ? $v2 : $v1; $a2 = $dir === 'desc' ? $v1 : $v2; if (!Str::isNumber($v1, $v2)) { $a1 = str_replace('.', '0', str_replace('_', '1', Str::changeCase($a1, 'lower'))); $a2 = str_replace('.', '0', str_replace('_', '1', Str::changeCase($a2, 'lower'))); $cmp = strcmp($a1, $a2); if (!empty($cmp)) { return $cmp; } } if ($a1 > $a2) { return 1; } elseif ($a1 < $a2) { return -1; } } return 0; } ); return $ar; }

Sorts the items of an indexed array based on a given $key. BBN is a suite of PHP and JS libraries and VueJS components - all open-source! bbn.io, build applications, the quick way

This website uses cookies to ensure you get the best experience on our website.