0

抱歉问了这么多问题——我今天写了很多代码,然后立即开始调试。

我想通过一个函数运行数组的每个元素,所以我选择做一个“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;
}

我不是在这里做点什么吗?

谢谢!

4

2 回答 2

3

该函数可能正在对字符串执行某些操作并将其返回(猜测一下。如果没有看到函数定义,我无法确定)。由于您没有对返回值做任何事情,因此您将丢弃函数返回的任何内容,因此您最终会得到未更改的字符串。

您可以通过引用传递参数

或者,将返回的结果存储在您的数组中:

foreach ($mod_array as $key=>$val) {
  $mod_array[$key] = convertImageMod($val);
}
于 2013-07-30T03:43:45.807 回答
2

使用foreach-loop with reference &将结果应用于数组。例子:

foreach($mod_array as &$string){
//                    ^ this
    $string = convertImageMod($string);
//  also, you need to assign return value of a function
//  to the current loop element ($string in this case).
}

或者使用array_map()函数。例子:

$mod_array = array_map('convertImageMod', $mod_array);

第二种选择效率较低且消耗更多内存。

于 2013-07-30T03:45:33.897 回答