PHP中所有RGB排列的数组 [英] Array of all RGB permutations in PHP

查看:84
本文介绍了PHP中所有RGB排列的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将由RGB值组成的所有可能颜色组成一个数组. r = 0 b = 0 g = 0至r = 255 b = 255 g = 255之间的每个置换.我的函数的想法是,在调用该函数时,您需要提供一个限制数,以便该函数返回一个由RGB值组成的数组,直到该数字为止,以停止返回全部1600万个字符.我下面的代码返回767个排列(256 * 3),如何得到此值以返回完整的1600万,直到我提供的限制数?

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;

}

推荐答案

嵌套循环是诀窍.请尝试以下示例.我已经用PHP range函数用foreach-loop替换了while循环,并将它们嵌套(即loop-inside-a-loop)到彼此之间:

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

参考:

http://php.net/range

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

这篇关于PHP中所有RGB排列的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆