简体   繁体   中英

PHP random colors for every row

I'm using chart.js for making pie chart. I'd like to have different colors for every slice that the while loop generates.

$pull_request = 'SELECT * FROM `oc_aa_affiliatecollclicktracking`';
$sqli = $db->query($pull_request);

$num_rows=mysqli_num_rows($sqli);
$cur_row=0;
var pieData = [
                <?php 
                while ($row = mysqli_fetch_array($sqli)) {      
                $color=intval(256*$cur_row/($num_rows-1));
                $cur_row++;
                echo    '{
                            value: '.$row["product_clicks"].',
                            color: "rgb(256,'.$color.')", // NEED TO BE RANDOM FOR EVERY ROW/SLICE
                            highlight: "#333",
                            label: "' .$row["product_id"].'"
                            },';
                }
                ?>
                ];

                var ctx = document.getElementById("chart-area").getContext("2d");
                window.myPie = new Chart(ctx).Pie(pieData);

} );

what I found makes random colors that changes on page refresh for the whole chart but not for the individual slice. Any idea?

You can use rand() function to get random numbers in specific range. Take a look here

Example:

$color = "#" . rand(10,100);

you can replace $color wherever you want.

If you want hex colors use this function

function random_color(){
    mt_srand((double)microtime()*1000000);
    $c = '';
    while(strlen($c)<6){
        $c .= sprintf("%02X", mt_rand(0, 255));
    }
    return $c;
}

If you are wanting the colours to randomly change visibly you are going to want a javascript solution, or if you want each slice to be a different colour each time the page loads, you could use something similar to this?

<?php 

function randomColour() {
    // Found here https://css-tricks.com/snippets/php/random-hex-color/
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    return $color;
}

while ($row = mysqli_fetch_array($sqli)) {                  
    echo    '{
        value: '.$row["product_clicks"].',
        color: '.randomColour().', // NEED TO BE RANDOM FOR EVERY ROW/SLICE
        highlight: "#333",
        label: "' .$row["product_id"].'"
    },';
}
?>

If you need the javascript solution, it would be more complex, as I do not know what happens in the .Pie() constructor, and how you would hook a colour changing element into it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM