tags:

views:

81

answers:

2

I have a program which presents a single random selection from the database each time it is run. What I would like to do is have the selections sorted by activity level and then have the selection title shown in a color which represents how active the random selection is.

For example: Item 1 is 45 days old, Item 2 is 61 days old and Item 3 is 10 days old.

The time range is: 1-45days (black), 46-60days (purple) and over 61days (blue)

I would like the PHP to sort the Items and when the program is run I would want the random item selected to be color coded so that: If Item 3 was chosen the text for the items title would be in color:#000000 If Item 1 was chosen the text for the items title would be in color:#770077 If Item 2 was chosen the text for the items title would be in color:#0000ff

The existing PHP program does not have any variable dealing with the age of the item or with coloring the items title. I am a almost complete novice with PHP (just bought Larry Ullman's book on the subject) so I do not even know if this can be done but I figured I would ask and see...

A: 

You could try the following method. Note that I have reduced the min/max by assuming the next array index in the sequence is always greater than the previous range.

// a mapping of ranges and their associated color
$range_map = array(
    array('color' => '#000000', 'min' => 1, 'max' => 46), 
    array('color' => '#770077', 'min' => 46, 'max' => 61),
    array('color' => '#0000ff', 'min' => 61, 'max' => 1000000)
);

$output = '';
foreach ($items as $item) {
    $color = '';
    foreach ($range_map as $range) {
        if ($item->days_old >= $range['min'] && $item->days_old < $range['max']) {
            $color = $range['color'];
            break;
        }
    }

    if (!empty($color)) {
        $output .= '<span style="color:' . $color . '">' . $YOUR_OUTPUT_HERE . '</span>';
    } else {
        $output .= $YOUR_OUTPUT_HERE;
    }
}

echo $output;

This is not the fastest solution but it can handle any number of cases with minimal modification.

cballou
A: 

ok. The following is the simplest way to do this:

$items[0]['title'] = 45;
$items[0]['daysold'] = 45;
$items[1]['title'] = 61;
$items[1]['daysold'] = 45;
$items[2]['title'] = 10;
$items[2]['daysold'] = 45;

$output = '';
foreach ($items as $item) {
    switch ($item['daysold']) {
        case ($item['daysold'] > 60):
            $color = "#00FFFF";
            break;
        case ($item['daysold'] > 45):
            $color = "#AA00FF";
            break;
        default:
            $color = "#000000";
    }
    $output .= '<span style="color:' . $color . '">' . $item['title'] . '</span>';
}
echo $output;

Item 1 should be black, Item 2 should be blue, and Item 3 should be black as well according to your requirements.

Joseph