我试图使用数组来返回特定的CSS代码,但我还没有找到一种自动的方法来根据数组更改数组的值。以下是我要做的:
$css = array(
"bgcolor" => array(
"wh" => array(* => "background-color:rgba(255,255,255,*);"),
"bk" => array(* => "background-color:rgba(0,0,0,*);")
),
"textcolor" => array(
"wh" => "color: #FFFFFF;",
"bk" => "color: #000000;"
),
"fade" => array(
"wh" => array(* => "box-shadow:#FFF 0px 0px *px;"),
"bk" => array(* => "box-shadow:#000 0px 0px *px;")
)
);
我使用*只是为了说明我正在努力实现的目标。这就是代码应该返回的内容:
$css["bgcolor"]["wh"][0.5]; // print background-color:rgba(255,255,255,0.5);
$css["textcolor"]["wh"]; // print color: #FFFFFF;
$css["fade"]["wh"][100]; // print box-shadow:#FFF 0px 0px 100px;
我不知道我想要的是不是可能,但我想是的,我只是不知道怎么做D
如果你使用的是PHP 5.3或更高版本,你可以通过使用匿名函数来实现这一点,比如:
<?php
$css = array(
'bgcolor' => array(
'wh' => function($s) {
return 'background-color: rgba(255, 255, 255, ' . $s . ');';
},
'bk' => function($s) {
return 'background-color: rgba(0, 0, 0, ' . $s . ');';
}
)
);
echo($css['bgcolor']['bk'](0.25)); // Returns rgba(0, 0, 0, 0.25)
echo(PHP_EOL);
echo($css['bgcolor']['wh'](0.75)); // Returns rgba(255, 255, 255, 0.75)
?>
我希望这就是你想要的。
使用函数
<?php
echo getStyle("bgcolor", "wh", 0.5);
echo getStyle("textcolor", "wh", 0.5);
echo getStyle("fade", "wh", 100);
function getStyle($style, $color, $px = 0) {
$css = array(
"bgcolor" => array(
"wh" => "background-color:rgba(255,255,255,*px);",
"bk" => "background-color:rgba(0,0,0,*px);"
),
"textcolor" => array(
"wh" => "color: #FFFFFF;",
"bk" => "color: #000000;"
),
"fade" => array(
"wh" => "box-shadow:#FFF 0px 0px *px;",
"bk" => "box-shadow:#000 0px 0px *px;"
)
);
return str_replace("*", $px, $css[$style][$color]);
}