doubushi0031
2011-12-14 14:45 阅读 2
已采纳

如何将foreach循环分配给变量?

I have this following code.

$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++;
  }

Is it possible to assign the above code to a variable $pointsvar

Everytime i use $pointsvar the above code should be printed. Please help. Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    doumaikuang4202 doumaikuang4202 2011-12-14 14:51

    Functions is your solution.

    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);
    
    点赞 评论 复制链接分享
  • drjyvoi734793 drjyvoi734793 2011-12-14 14:49

    use .= to assign something to the end of a variable... Something like this:

    $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;
    

    If you want to call something like this alot, just move this into a function , and pass in the $points array.

    点赞 评论 复制链接分享
  • dqyy38265 dqyy38265 2011-12-14 14:50

    Is it ok if $pointsvar is static? (set once, then always at that value?) Is so, just change your echoes to become assignents...

    $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++; 
      } 
    
    点赞 评论 复制链接分享
  • dqrmkdu25623 dqrmkdu25623 2011-12-14 14:52

    Use a function... not a variable

    function pointvar() {
        //Your code here    
    }
    

    If you want get or set your variable

    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
    
    点赞 评论 复制链接分享

相关推荐