我有以下代码。
$sn_count = 1;
foreach($points as $point){
echo "<div class=\"points\">";
echo "<div class=\"serial\">".$sn_count."</div>";
echo "<div class=\"pointsdesc\">";
echo $point['points_description'];
echo "</div></div>";
$sn_count++;
}
是否可以将上述代码分配给变量$pointsvar
每次使用$pointsvar
时,都应打印上述代码。请帮忙。
感谢
答案 0 :(得分:3)
功能是您的解决方案。
function printPointVars($points)
{
$sn_count = 1;
$html = '';
foreach($points as $point){
$html .= "<div class=\"points\">"
. "<div class=\"serial\">".$sn_count."</div>"
. "<div class=\"pointsdesc\">"
. $point['points_description']
. "</div></div>";
$sn_count++;
}
echo $html;
}
printPointVars($points);
答案 1 :(得分:1)
使用函数...而不是变量
function pointvar() {
//Your code here
}
如果您想获取或设置变量
function pointvar($var = null) {
if(!empty($var)) {
$pointvar = $var;
}
//Your code here
return $pointvar;
}
pointvar(12); //Set pointvar and execute your code
$newVar = pointvar(); //Get pointvar value and execute your code
答案 2 :(得分:0)
使用。=将一些东西分配到变量的末尾......这样的东西:
$sn_count = 1;
$pointsvar = "";
foreach($points as $point){
$pointsvar .= "<div class=\"points\">";
$pointsvar .="<div class=\"serial\">".$sn_count."</div>";
$pointsvar .="<div class=\"pointsdesc\">";
$pointsvar .=$point['points_description'];
$pointsvar .="</div></div>";
$sn_count++;
}
echo $pointsvar;
如果你想调用类似的东西,只需将其移动到一个函数中,然后传入$ points数组。
答案 3 :(得分:0)
如果$ pointsvar是静态的,可以吗? (设置一次,然后总是在那个值?)是这样,只需改变你的回声成为受让人......
$pointsvar = '';
$sn_count = 1;
foreach($points as $point){
pointsvar = pointsvar."<div class=\"points\">";
pointsvar = pointsvar."<div class=\"serial\">".$sn_count."</div>";
pointsvar = pointsvar."<div class=\"pointsdesc\">";
pointsvar = pointsvar.$point['points_description'];
pointsvar = pointsvar."</div></div>";
$sn_count++;
}