2016-05-31 88 views
1

我想爲php做十進制 - >十六進制顏色函數,但像eg。它打印出ff19a,即使我想要它做ff190a。我假設我的foreach函數中的if語句沒有通過,老實說,我不知道爲什麼。我也試着爲什麼我的foreach函數不能運行?

$value = "0$value"; 

不工作,要麼在$十六進制行[$值]

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

echo decimalColors(255, 25, 10); 

我很想得到一個解決方案,如果可能的解釋爲什麼它不起作用。

謝謝!

回答

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數組,這樣就可以改變陣列的值參考,而不是堅持,這將不會產生所需的效果。

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

使用舊foggoten的sprintf :)

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

我建議用splash58的回答會,但我懷疑你」重新嘗試學習這些東西,不僅僅是高效地完成它,所以我會在這裏添加一些細節。

你對函數的工作原理有一些誤解,他們應該採取一些輸入和return一些輸出。你的不是返回任何輸出,而是你的echoing從功能(這是壞的形式)。

此外,你正在修改一個值,然後回顯另一個,這就是爲什麼你沒有看到變化反映在你的輸出。

最後,您需要循環使用foreach使用the key and the value。您正在修改的值分別爲$hexadecimal["ff"],$hexadecimal["19"]$hexadecimal["a"],這當然不存在。相反,您要修改$hexadecimal[0],$hexadecimal[1]$hexadecimal[2]。另一種選擇是使用foreachby 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()功能簡單卡紙的數組中的元素在一起。

+0

我認爲這裏的所有答案都是有效的,你可以從中學到很多東西。總是有很多方法可以做同樣的事情。重要的是要*學習*。 –

+0

@ miken32等待我對$ key => $值最感到困惑,因爲這不是一個有鍵和值的多維數組。我只是將數字存儲到$十六進制,所以沒有一個鍵/值實例正確嗎? – mathn00b

+0

@ mathn00b當你像這樣構建一個數組時,會有隱式數字鍵集。嘗試在函數返回之前粘貼一個'print_r($ hexadecimal);',你會看到它們爲0-2。我在那個問題的答案中犯了一個錯誤,我修正了這個問題。多維數組是數組的數組。 – miken32

相關問題