Pregunta

I am trying to make an array of all the possible colours made out of RGB values. Every permutation between r=0 b=0 g=0 to r=255 b=255 g=255. The idea of my function is that when it's called you supply a limit number so that the function returns an array of RGB values up to this number to stop it returning all 16 million. The code I have below returns 767 permutations (256 * 3) how do I get this to return the full 16 million up to the limit number I provide?

function colourArray($number) {

    $r = 0;

    $g = 0;

    $b = 0;

    $i = 0;

    while ($i <= $number) {

        $colours[] = array($r,$g,$b);

        $r++;

        $i++;

    }

    $i = 0;

    while ($i <= $number) {

        $colours[] = array($r,$g,$b);

        $g++;

        $i++;

    }

    $i = 0;

    while ($i <= $number) {

        $colours[] = array($r,$g,$b);

        $b++;

        $i++;

    }


    return $colours;

}
¿Fue útil?

Solución

Nesting your loops is the trick. Try the following example. I've replaced your while-loops by foreach-loops with the PHP range function, and nested (i.e. loop-inside-a-loop) them inside eachother:

function colourArray($number) {
        $colours = array();
        foreach(range(0,$number) as $r) {
            foreach(range(0,$number) as $g) {
                foreach(range(0,$number) as $b) {
                    $colours[] = array($r,$g,$b);
                }
            }
        }
        return $colours;
}

References:

http://php.net/range

http://php.net/manual/en/control-structures.foreach.php

Otros consejos

I almost agree with DickW, but I'm partial to for() loops for numeric ranges.

<?php

function color_array($range)
{
    $result = array();

    for ($r = 0; $r <= $range; $r++) {
        for ($g = 0; $g <= $range; $g++) {
            for ($b = 0; $b <= $range; $b++) {
                $result[] = array($r, $g, $b);
            }
        }
    }

    return $result;
}

print_r(color_array(5));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top