2016-07-21 138 views
0

我已經使用了Google和這個網站的各種方法,但不知何故我的問題沒有得到解決。PHP:將數組推入數組

這是我的問題:我有一個名爲$color的數組,我想從一個函數內向這個(多維)數組添加數組。

$color = array(); 

function hex2RGB($hex){ 
    $hex = ltrim($hex,'#'); 
    $a = hexdec(substr($hex,0,2)); 
    $b = hexdec(substr($hex,2,2)); 
    $c = hexdec(substr($hex,4,2)); 
    $rgb = array($a, $b, $c); 
    array_push($color,$rgb); 
} 

hex2RGB("#97B92B"); 
hex2RGB("#D1422C"); 
hex2RGB("#66CAEA"); 

我知道該函數創建一個良好的「rgb」與3個值的數組,我用屏幕輸出測試。但使用array_push$color[] = $rgb;不會將該陣列添加到$color陣列。沒有錯誤顯示,「顏色」 - 陣列只是空着。

+0

你就不能對最終的簡單陣列'return'併爲其分配 – Ghost

+1

[可變範圍(http://php.net/ manual/en/language.variables.scope.php) – FirstOne

+0

旁註:此用戶[貢獻說明](http://php.net/manual/en/function.sscanf.php#25190)顯示了一個很好的方法來轉換.. – FirstOne

回答

0

您需要全球化您的$ color數組才能在函數內使用它。

<?php 
$color = array(); 

function hex2RGB($hex){ 
global $color; // magic happens here 

$hex = ltrim($hex,'#'); 
$a = hexdec(substr($hex,0,2)); 
$b = hexdec(substr($hex,2,2)); 
$c = hexdec(substr($hex,4,2)); 
$rgb = array($a, $b, $c); 
array_push($color,$rgb); 
} 

解決了您的問題。

更多信息請參考PHP的教程的Scope

0

見下文。你需要允許在功能通過使用「全球」關鍵字可以使用全局變量$顏色:

$color = array(); 

function hex2RGB($hex){ 
global $color; //<----------------this line here is needed to use $color 
$hex = ltrim($hex,'#'); 
$a = hexdec(substr($hex,0,2)); 
$b = hexdec(substr($hex,2,2)); 
$c = hexdec(substr($hex,4,2)); 
$rgb = array($a, $b, $c); 
array_push($color,$rgb); 
} 

hex2RGB("#97B92B"); 
hex2RGB("#D1422C"); 
hex2RGB("#66CAEA"); 
1

您需要通過參考

function hex2RGB($hex, &$color){ // '&' means changes to $color will persist 
    ... 
} 
$color = []; 
hex2RGB('#...',$color);//after this line, $color will contain the data you want 

我到$color陣列的功能通過會比使用global更有利於這個功能,因爲使用這種方法,您可以精確地控制哪個數組會被修改(您在調用函數時將其傳遞給它)。使用global可能會導致意想不到的後果,如果您在調用函數時忘記它會更改範圍中的其他變量。更好的設計是讓你的代碼模塊化(只需搜索關於使用global變量的建議)。

+0

我一直在尋找這個(一個選項_without_ global)+1 – FirstOne