2013-05-08 123 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>