抱歉提出了很多问题 - 我今天写了很多代码,然后开始一次调试。数组的foreach元素,执行函数
我想通过一个函数运行数组中的每个元素,所以我选择了做一个“foreach”循环。这里是我的代码:
//Set up mod and polarity associative arrays
$mod_array = array(
"image_mod1" => "$page_mod1",
"image_mod2" => "$page_mod2",
"image_mod3" => "$page_mod3",
"image_mod4" => "$page_mod4",
"image_mod5" => "$page_mod5",
"image_mod6" => "$page_mod6",
"image_mod7" => "$page_mod7",
"image_mod8" => "$page_mod8"
);
$polarity_array = array(
"image_polarity1" => "$page_polarity1",
"image_polarity2" => "$page_polarity2",
"image_polarity3" => "$page_polarity3",
"image_polarity4" => "$page_polarity4",
"image_polarity5" => "$page_polarity5",
"image_polarity6" => "$page_polarity6",
"image_polarity7" => "$page_polarity7",
"image_polarity8" => "$page_polarity8"
);
foreach($mod_array as $string)
{
convertImageMod($string);
}
foreach($polarity_array as $string)
{
convertImagePolarity($string);
}
然而,当我回声字符串(echo $page_polarity6;
),即回声文字,仿佛尚未应用的功能。
这里是我的函数定义:
function convertImageMod($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
$stringlength -= 3;
$string = substr ($string, 0, $stringlength);
$string = strtolower ($string);
$string = "<img src=\"images/items/{$string}.png\">";
return $string;
}
function convertImagePolarity($string)
{
$string = "<img src=\"images/items/{$string}.png\">";
return $string;
}
我不能做的事情吗?
谢谢!
除非您使用引用,否则需要将函数的结果重新分配到数组中。 – Barmar
即使您确实分配了结果,它也会更改数组,而不是其数值在数组中的变量。 – Barmar
顺便说一句,你不需要把变量放在数组赋值中的引号内。 – Barmar