2016-07-21 136 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