我试图弄清楚如何在PHP函数中使用PHP数组。我能够使用字符串替换来用函数内部的$counter变量替换{count}。但是,我无法对字符串中的数组执行相同的操作。我尝试使用For循环中的$i来选择数组索引,但这不起作用。我还尝试对数组索引使用{count},然后使用字符串替换将其替换为$counter变量。这也不起作用。如果有人能指出正确的方向,我会指手画脚。谢谢您抽时间见我。
<?php
function repeatHTML($repeatCount, $repeatString){
$counter = 1;
for ($i = 1; $i <= $repeatCount; $i++) {
$replacedRepeatString = str_replace('{count}', $counter, $repeatString);
echo $replacedRepeatString;
$counter++;
}
}
$titleContent = array('orange', 'apple', 'grape', 'watermelon');
repeatHTML(4, '<div class="image-{count}">'.$titleContent[$i].'</div>');
?>输出示例:
<div class="image-1">orange</div>
<div class="image-2">apple</div>
<div class="image-3">grape</div>
<div class="image-4">watermelon</div>发布于 2015-06-01 20:17:44
我不知道你为什么需要这个,但你可以这样做:
function repeatHTML( $repeatHTML, $repeatArray ) {
foreach ( $repeatArray as $key => $repeatValue ) {
$replacedRepeatString = str_replace('{count}', $key, $repeatHTML);
$replacedRepeatString = str_replace('{value}', $repeatValue, $repeatHTML);
echo $replacedRepeatString;
}
}
// 1 => only if you want to start from 1, instead of 0
$titleContent = array( 1 => 'orange', 'apple', 'grape', 'watermelon' );
repeatHTML( '<div class="image-{count}">{value}</div>', $titleContent );如果要在函数中使用数组,则必须将其设置为单独的属性。
现在,如果要遍历整个数组,则不需要使用$repeatCount属性。
编辑:
您还可以通过结合HTML和PHP来创建自己的“模板”。
<?php
$content = array( 1 => 'orange', 'apple', 'grape', 'watermelon' );
foreach ( $content as $key => $value )
{
?> <div class="image-<?=$key?>"><?=$value?></div> <?php
}不过,我建议使用现有的模板引擎。这段代码不那么清晰,可能会变得非常混乱。
发布于 2015-06-01 20:28:13
我认为您的代码中有更多的问题。你不需要更换任何东西。您可以这样定义和调用您的函数:
function repeatHTML($arr){ // add array as parameter
$content = ""; // initialize variable
$i = 0; // initialize variable
foreach($arr as $k=>$n){ // loop through array
$content .= '<div class="image-'.$i.'">'.$n.'</div>'; // fill variable with html
$i++; // increment counter variable
}
return $content;
}
$titleContent = array(0=>'orange', 1=>'apple', 2=>'grape', 3=>'watermelon'); // fill array
echo repeatHTML($titleContent); // call function发布于 2015-06-01 20:34:28
我稍微清理了一下,并编写了一个通用函数来帮助您处理数组。请注意,我同意这不一定是最好的选择-但它确实解决了你的问题,你想它的方式。
function repeatHTML($count, $string, $array){
foreach ($array as $index => $value) {
echo str_replace(['{count}', '{value}'], [$index + 1, $value], $string);
}
}
$titleContent = array('orange', 'apple', 'grape', 'watermelon');
repeatHTML(4, '<div class="image-{count}">{value}</div>', $titleContent);这将输出<div class="image-1">orange</div><div class="image-2">apple</div><div class="image-3">grape</div><div class="image-4">watermelon</div>,如果需要空行,可以很容易地在echo语句中添加换行符或<br>。
如果您需要帮助来解释这个函数是如何工作的,请告诉我。
https://stackoverflow.com/questions/30582382
复制相似问题