2014-03-26 31 views
0

我在計算如何使我的函數返回轉換字符串的連接列表時遇到了一些麻煩。目標是處理2個並行數組,並使用一個數組中的值('U'或'L')使並行數組中的值(單詞)使用循環轉換爲全部大寫或小寫。PHP如何處理並行數組,轉換並返回連接值

我想返回轉換結果的連接列表。

我不想使用任何參數。

現在它只是返回第一個單詞,我不知道如何使它返回整個單詞。任何幫助表示讚賞!

<?php 

$case[0]='U'; // I just made these arrays up for the purpose of testing 
$case[1]='L'; // the $case array values will be either U or L 
$case[2]='U'; 
$case[3]='L'; 

$strings[0]='tHese'; // the $strings array values are words of varying case 
$strings[1]='aRe'; 
$strings[2]='rAndoM'; 
$strings[3]='wOrDs'; 



function changeCase() { 
    global $case;  
    global $strings; 

    $total = ""; 
    for ($i = 0; $i < sizeof($case); $i++) { 
     if ($case[$i] == "U") return strtoupper($strings[$i]); 
     elseif ($case[$i] == "L") return strtolower($strings[$i]); 
     $total = $total + $strings[$i]; //the returned value should look like THESEareRANDOMwords 
    } 
    return $total; 
}; 

echo changeCase(); 

?>

+0

由於您使用的是函數,因此您最好將數組作爲參數傳遞,而不是將其作爲全局變量來訪問。 – rath

+1

使用return關鍵字退出該函數。在你的for循環中不用return就可以重寫 –

回答

1
<?php 

function changeCase ($case, $strings) { 
    $total = ''; 
    foreach($case as $i=>$type) 
     $total .= ($type=='U') ? strtoupper($strings[$i]) : strtolower($strings[$i]); 
    return $total; 
} 

$case[0]='U'; // I just made these arrays up for the purpose of testing 
$case[1]='L'; // the $case array values will be either U or L 
$case[2]='U'; 
$case[3]='L'; 

$strings[0]='tHese'; // the $strings array values are words of varying case 
$strings[1]='aRe'; 
$strings[2]='rAndoM'; 
$strings[3]='wOrDs'; 

echo changeCase($case, $strings); 
1

您正在使用循環return,這將讓你離開的功能。你永遠不會到達$total=...部分。

+0

哦,好吧,我想因爲返回是在關閉for循環的大括號之後,所以沒關係。 – user3466010

0

array_map()是完美的。

$case[0]='U';  
$case[1]='L';  
$case[2]='U'; 
$case[3]='L'; 

$strings[0]='tHese';  
$strings[1]='aRe'; 
$strings[2]='rAndoM'; 
$strings[3]='wOrDs'; 

// Set up an anonymous function to run on $case, and pass in $strings 
$funct = function($value, $key) use ($strings) {    
    if($value == "U") 
     return strtoupper($strings[$key]); 
    else 
     return strtolower($strings[$key]); 
}; 

// Pass in our keys as an additional parameter, this is not usual 
// but in this case we need the keys to access the $strings array 
$results = array_map($funct, $case, array_keys($case)); 

var_dump(implode("", $results)); 
相關問題