Для получения полного доступа
зарегистрируйтесь.
RSS

All snippets tagged with "sort" tag



dignityinside
  • Reputation: 26
  • Snippets: 21
  • Revisions: 1

Function to sort an array according to its keys which are floats casted as strings.

function sort_string_float($a, $b) {

	$a = (float) $a;
	$b = (float) $b;

	if ($a == $b) {
		return 0;
	}

	return $a < $b ? -1 : 1;

}

// use
uksort($l1_data, 'self::sort_string_float');
samdark
  • Reputation: 349
  • Snippets: 57
  • Revisions: 5

There are cases when you need to make sure keys specified are in the beginning of an array in the exact order they are specified.

$data = [
    'orange' => 'orange',
    'apple' => 'tasty',
    'carpet' => 'old',
    'car' => 'fast',
];

$result = orderByKeys($data, ['car', 'carpet']);

Would result in:

$data = [
    'car' => 'fast',
    'carpet' => 'old',
    'orange' => 'orange',
    'apple' => 'tasty',    
];
function orderByKeys(array $array, array $keys)
{
    foreach ($keys as $k => $v) {
        if (!array_key_exists($v, $array)) {
            unset($keys[$k]);
        }
    }

   return array_replace(array_flip($keys), $array);
}