搜索读取数组值的PHP函数

时间:2015-11-06 15:51:53

标签: php arrays string

我尝试创建一个函数来代替if条件,该函数读取数组的所有值和位置,然后调用一个函数。我检查文档但无法找到解决方案。我可以在这里使用任何PHP功能吗?

function one() {
    echo '#btn1 {';
        echo 'animation-name:example;';
        echo 'animation-duration:1s;';
        echo 'animation-delay:0.5s;';
    echo '}';       
}

function two() {
    echo '#btn2 {';
        echo 'animation-name:example;';
        echo 'animation-duration:1s;';
        echo 'animation-delay:0.5s;';
    echo '}';       
}

$code = 12;
$arr1 = str_split($code);

if ($arr1[0] == 1) {
    one();
}
if ($arr1[0] == 2) {
    two();
}
if ($arr1[1] == 1) {
    one();
}
if ($arr1[1] == 2) {
    two();
}
if ($arr1[2] == 1)....
// Continues like this for about 36 times

2 个答案:

答案 0 :(得分:3)

这样的东西?

function one() {
    echo '#btn1 {';

        echo 'animation-name:example;';
        echo 'animation-duration:1s;';
        echo 'animation-delay:0.5s;';
    echo '}';       
}
function two() {
    echo '#btn2 {';

        echo 'animation-name:example;';
        echo 'animation-duration:1s;';
        echo 'animation-delay:0.5s;';
    echo '}';       
}

$code = 12;
$arr1 = str_split($code);

foreach ($arr1 as $value) {
    switch($value) {
        case 1:
            one();
        break;
        case 2:
            two();
        break;
    }
}

一切都变得更加紧凑

$code = 12;
$arr1 = str_split($code);
$css = '';
foreach ($arr1 as $value) {
    $css .= '#btn' . $value . ' {';
    $css .= '    animation-name:example;';
    $css .= '    animation-duration:1s;';
    $css .= '    animation-delay:0.5s;';
    $css .= '}'; 
}

echo $css; // output variable

答案 1 :(得分:0)

这是你在找什么?

$map = array(1 => 'one', 2 => 'two', 3 => 'tri', 4 => 'four');

function one(){
    echo 'I am inside function one()';
}

function two(){
    echo 'I am inside function two()';
}

function tri(){
    echo 'I am inside function tri()';
}

$str = '1324';
for($i = 0; $i<strlen($str); $i++){
    echo 'Number: ' . $str[$i] . '<br>';
    echo 'Function: ' . $map[$str[$i]] . '<br>';
    echo 'CALLING IT: ';
    $map[$str[$i]]();
    echo '<br> ---------------------------- <br>';
}

请注意,如果该函数不存在(在这种情况下为four()),则会导致错误。

<强>输出:

Number: 1
Function: one
CALLING IT: I am inside function one()
---------------------------- 
Number: 3
Function: tri
CALLING IT: I am inside function tri()
---------------------------- 
Number: 2
Function: two
CALLING IT: I am inside function two()
---------------------------- 
Number: 4
Function: four
CALLING IT: E_ERROR : type 1 -- Call to undefined function four() -- at line 21