Last active
December 10, 2015 19:38
-
-
Save cmbuckley/4482601 to your computer and use it in GitHub Desktop.
Answer for http://stackoverflow.com/q/14209509
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 | |
// quick and dirty color generator | |
function getColors($count) { | |
$colors = array(); | |
for ($i = 0; $i < $count; $i++) { | |
$colors[] = '#' . substr(md5("color$i"), 0, 6); | |
} | |
return $colors; | |
} | |
// names | |
$names = array( | |
array('sanitized' => 'lisa', 'original' => 'Lisa', 'weight' => 5, 'color' => 'blank'), | |
array('sanitized' => 'jack', 'original' => 'Jack', 'weight' => 1, 'color' => 'blank'), | |
array('sanitized' => 'jerry', 'original' => 'Jerry', 'weight' => 2, 'color' => 'blank'), | |
array('sanitized' => 'paul', 'original' => 'Paul', 'weight' => 4, 'color' => 'blank'), | |
array('sanitized' => 'ron', 'original' => 'Ron', 'weight' => 2, 'color' => 'blank'), | |
array('sanitized' => 'harry', 'original' => 'Harry', 'weight' => 3, 'color' => 'blank'), | |
array('sanitized' => 'mike', 'original' => 'Mike', 'weight' => 4, 'color' => 'blank'), | |
array('sanitized' => 'lisa', 'original' => 'Lisa', 'weight' => 3, 'color' => 'blank'), | |
array('sanitized' => 'ron', 'original' => 'Ron', 'weight' => 5, 'color' => 'blank'), | |
array('sanitized' => 'dylan', 'original' => 'Dylan', 'weight' => 1, 'color' => 'blank'), | |
); | |
$colors = getColors(count($names)); | |
$combined = array(); | |
// loop once to build the combined array and set the colors | |
foreach ($names as &$name) { | |
if (!isset($combined[$name['sanitized']])) { | |
$combined[$name['sanitized']] = array( | |
'original' => $name['original'], | |
'weight' => $name['weight'], | |
'color' => array_pop($colors), | |
'count' => 1, | |
); | |
} elseif ($combined[$name['sanitized']]['count'] < 3) { | |
$combined[$name['sanitized']]['weight'] += $name['weight']; | |
$combined[$name['sanitized']]['count']++; | |
} | |
$name['color'] = $combined[$name['sanitized']]['color']; | |
} | |
// loop again to blank any colors where name only appeared once | |
foreach ($names as &$name) { | |
if ($combined[$name['sanitized']]['count'] === 1) { | |
$combined[$name['sanitized']]['color'] = $name['color'] = 'blank'; | |
} | |
} | |
var_dump($combined, $names); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment