[英]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.