2013-07-30 70 views
0

抱歉提出了很多问题 - 我今天写了很多代码,然后开始一次调试。数组的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; 
} 

我不能做的事情吗?

谢谢!

+0

除非您使用引用,否则需要将函数的结果重新分配到数组中。 – Barmar

+0

即使您确实分配了结果,它也会更改数组,而不是其数值在数组中的变量。 – Barmar

+2

顺便说一句,你不需要把变量放在数组赋值中的引号内。 – Barmar

回答

2

使用foreach -loop与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); 

第二种方法效率较低,消耗的内存也较多。

+0

完美地工作,我会在6分钟内接受这个答案哈哈。 我使用了顶级的代码。 此外,如果我执行 $ array2 = array_filter($ array1); 将数组2与数组1相同,删除空值? – SteelyDan

+0

@SteelyDan是的。这将是。 – BlitZ

3

该函数可能对字符串做了一些事情并将其返回(猜测,如果没有看到函数定义,我不能确定)。由于你没有对返回值做任何事情,所以你放弃了函数返回的任何东西,因此你最终得到的字符串不变。

您可以pass the arguments via reference

或者存储返回的结果数组中:

foreach ($mod_array as $key=>$val) { 
    $mod_array[$key] = convertImageMod($val); 
}