Created
March 22, 2012 13:44
-
-
Save alexkingorg/2158428 to your computer and use it in GitHub Desktop.
Sort colors from dark to light
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 | |
function cf_sort_hex_colors($colors) { | |
$map = array( | |
'0' => 0, | |
'1' => 1, | |
'2' => 2, | |
'3' => 3, | |
'4' => 4, | |
'5' => 5, | |
'6' => 6, | |
'7' => 7, | |
'8' => 8, | |
'9' => 9, | |
'a' => 10, | |
'b' => 11, | |
'c' => 12, | |
'd' => 13, | |
'e' => 14, | |
'f' => 15, | |
); | |
$c = 0; | |
$sorted = array(); | |
foreach ($colors as $color) { | |
$color = strtolower(str_replace('#', '', $color)); | |
if (strlen($color) == 6) { | |
$condensed = ''; | |
$i = 0; | |
foreach (preg_split('//', $color, -1, PREG_SPLIT_NO_EMPTY) as $char) { | |
if ($i % 2 == 0) { | |
$condensed .= $char; | |
} | |
$i++; | |
} | |
$color_str = $condensed; | |
} | |
$value = 0; | |
foreach (preg_split('//', $color_str, -1, PREG_SPLIT_NO_EMPTY) as $char) { | |
$value += intval($map[$char]); | |
} | |
$value = str_pad($value, 5, '0', STR_PAD_LEFT); | |
$sorted['_'.$value.$c] = '#'.$color; | |
$c++; | |
} | |
ksort($sorted); | |
return $sorted; | |
} |
nice ! You saved the day.
Unfortunatly not really working for me.
I have written by my own ;)
function cf_sort_hex_colors($colors) {
$sorted = [];
foreach ($colors as $color) {
if (strlen($color) == 6) {
$key = "";
for($i=0;$i<6;$i++)
{
$key .= sprintf('%02d',$this->map[substr($color, $i, 1)]);
}
$sorted[$key] = $color;
}
}
ksort($sorted);
return array_values($sorted);
}
The color array is that way : ['eeeeee','ffffff', ...]. If the color code are using # juste add (as seen in the upper example :
$color = strtolower(str_replace('#', '', $color));
at the line 10 of the function replace $sorted[$key] = $color;
by $sorted[$key] = '#'.$color;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome! thx for your help on this one.