2015-11-06 74 views
0

我嘗試創建而不是if條件函數,它讀取數組的所有值和位置,然後調用函數。我檢查文檔,但無法找到解決方案。有沒有我可以在這裏使用的任何PHP函數?搜索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 
+0

什麼你真的想達到什麼目的? – Akshay

+0

類似於http://php.net/manual/en/function.array-walk.php – sanderbee

+0

我想要安全的代碼。這只是我的一段代碼和我的條件,還有36:D – klamertd

回答

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 
+0

謝謝你的哥們!最後一個問題:如果'$ code = 34267'並且我有七個按鈕,那麼可能是這樣的,第一個按鈕,第四個按鈕,第二個按鈕等等變成動畫?謝謝你的這篇文章;) – klamertd

+2

@klamertd,據我瞭解你剛剛說的**是的** :) – Thaillie

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