Array of all RGB permutations in PHP

让人想犯罪 __ 提交于 2020-01-07 04:33:09

问题


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;

}

回答1:


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




回答2:


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));


来源:https://stackoverflow.com/questions/21268983/array-of-all-rgb-permutations-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!