为什么我的foreach函数不运行?

时间:2016-05-31 04:00:14

标签: php

我正在尝试做一个小数 - > php的十六进制颜色函数,但是像eg。它打印出ff19a,即使我想要它做ff190a。我假设我的foreach函数中的if语句没有通过,老实说我不知道​​为什么。我也试过了

=> Apple.all
[
    [0] #<Apple:0x007fdff8b49b70> {
                           :id => 1,
                      :user_id => 1,
    }
]

=> apples
[]

=> apples.rotten
[
    [0] #<Apple:0x007fdff8b49b70> {
                           :id => 1,
                      :user_id => 1
    }
]

对于$ hexadecimal [$ value]

中的行无效
$value = "0$value";

我希望得到一个解决方案,如果可能的话,解释为什么它不起作用。

谢谢!

4 个答案:

答案 0 :(得分:2)

我建议使用splash58的答案,但我怀疑你正在尝试学习这些东西,而不仅仅是有效地完成它,所以我会在这里添加一些细节。

你对功能如何运作有一些误解;他们应该接受一些输入和return一些输出。你没有返回任何输出,而是你从函数echoing(这是一个糟糕的形式。)

此外,您正在修改一个值,然后回显另一个值,这就是您没有看到输出中反映的更改的原因。

最后,您需要使用foreachthe key and the value进行循环。您修改的值为$hexadecimal["ff"]$hexadecimal["19"]$hexadecimal["a"],当然这些值不存在。您想要修改$hexadecimal[0]$hexadecimal[1]$hexadecimal[2]。另一种选择是使用foreach by reference,但这可能会等待以后!

您的代码可能看起来更像这样:

<?php
function hexColors($red, $green, $blue){
    $hexadecimal = [dechex($red), dechex($green), dechex($blue)];
    foreach ($hexadecimal as $key=>$value) {
        if (strlen($value) == 1){
            $hexadecimal[$key] = "0".$value;
        }
    }
    return implode("", $hexadecimal);
}

echo hexColors(255, 25, 10);

注意,implode()函数只是将数组的元素绑定在一起。

答案 1 :(得分:1)

我认为你需要改变这个

function decimalColors($red, $green, $blue){
    $hexadecimal = [dechex($red), dechex($green), dechex($blue)];
    foreach ($hexadecimal as $value) {
        if (strlen($value) == 1){
            $hexadecimal[$value] = "0".$value;
        }
        echo $value;
    }
}

到此:

function decimalColors($red, $green, $blue){
    $hexadecimal = [dechex($red), dechex($green), dechex($blue)];
    foreach ($hexadecimal as &$value) {
        if (strlen($value) == 1){
            $value = "0".$value;
        }
        echo $value;
    }
}

它使用foreach数组的引用形式,以便您可以通过引用更改数组值,而不是被 >值,不会产生预期的效果。

答案 2 :(得分:1)

使用旧的foggoten sprintf :)

function decimalColors($red, $green, $blue){
     return sprintf('%02x%02x%02x', $red, $green, $blue);
}

答案 3 :(得分:0)

您可以使用0为您的值填充字符串并返回:

function decimalColors($red, $green, $blue)
    {
        return str_pad(dechex($red),2,0,STR_PAD_LEFT).str_pad(dechex($green),2,0,STR_PAD_LEFT).str_pad(dechex($blue),2,0,STR_PAD_LEFT);
    }

echo decimalColors(255, 10, 20);