[英]Using a PHP array inside of a PHP function?
我试图弄清楚如何在PHP函数中使用PHP数组。 我可以使用字符串替换将{count}替换为函数内部的$ counter变量。 但是我无法对字符串内部的数组执行相同的操作。 我尝试从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>
我不知道您为什么需要这个,但是您可以执行以下操作:
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
}
不过,我建议您使用现有的模板引擎。 这段代码不太清楚,可能会变得很混乱。
我认为您的代码有更多问题。 您不需要更换任何东西。 您可以这样定义和调用函数:
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
我整理了一下并编写了一个通用函数来帮助您处理数组。 请注意,我同意这不一定是最好的选择-但这确实可以按您希望的方式解决您的问题。
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>
。
如果您需要任何帮助解释该功能的工作原理,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.