我在弄清楚如何使函数返回转换字符串的串联列表时遇到了一些问题。目标是处理2个并行数组,并使用一个数组中的值('U'或'L'(,使用循环将并行数组中的数值(单词(转换为大写或小写。
我想返回转换结果的串联列表。
我不希望使用任何参数。
现在它只是返回第一个单词,我不知道如何让它返回整个单词数组。感谢您的帮助!
<?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 ();
?>
<?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);
您在循环中使用return
,这将使您退出函数。您永远无法到达$total=...
部分。
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));