2013-05-08 124 views
0

我有一個PHP對象,我正在循環,我知道有2件事情是用這個對象來定義的,我將永遠不需要循環超過12次(1-12)和我也將永遠不得不循環至少一次。PHP循環對象基於對象長度操作輸出

我的問題來了,當對象超過6個項目,好像它超過6個項目我需要將結果拆分爲2 <ol>和爲我的生活我想不出一個很好的方式來做到這一點?

這裏是我的嘗試,

<?php $count = 1; ?> 
    <?php if(is_object($active_projects)) : ?> 
     <div class="col_1"> 
      <?php if($count < 2) : ?> 
       <strong>Active projects</strong> <a href="/projects" class="view">View All</a> 
      <?php endif; ?> 
       <ol <?php echo ($count > 1 ? " class='no-header'" : ""); ?>> 
        <?php foreach($active_projects as $project) : ?> 
         <li><a href=""><?php echo $project->project_name; ?></a></li> 
         <?php $count ++; ?> 
         <?php endforeach; ?> 
       </ol> 
     </div> 
    <?php endif; ?> 

現在我嘗試顯示一個列表中的所有結果,怎麼能是否有對象多於6項,在2讓我輸出2分裂環<div class="col_1">每個列表中有6個項目?

回答

0

試試這個:

<?php 
//create an object with 12 items 
$obj = new stdClass(); 
for($i = 1; $i <= 12; $i++) 
{ 
    $project = "project_$i"; 
    $obj->{$project} = new stdClass(); 
    $obj->{$project}->name = "Project $i"; 
} 

function wrapInLi($projectName) 
{ 
    return "<li>$projectName</li>\n"; 
} 

function wrapInOl($arrayOfLi) 
{ 
    $returnString = "<ol>\n"; 
    foreach ($arrayOfLi as $li) 
    { 
     $returnString .= $li; 
    } 
    return $returnString . "</ol>\n"; 
} 

/* 
* The classname is adjustable, just in case 
*/ 
function wrapInDiv($ol, $class) 
{ 
    return "<div class='$class'>\n$ol</div>\n"; 
} 


?> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title></title> 
    </head> 
    <body> 
     <?php 
     $arrayOfLi = array(); 
     foreach($obj as $project) 
     { 
      //fill an array with list-items 
      $arrayOfLi[] = wrapInLi($project->name); 

      //six list-items? wrap it 
      if(count($arrayOfLi) === 6) 
      { 
       //wrap in unordered list 
       $ol = wrapInOl($arrayOfLi); 
       //wrap in div and echo 
       echo wrapInDiv($ol, 'col_1'); 
       //reset array 
       $arrayOfLi = array(); 
      } 
     } 

     ?> 
    </body> 
</html>