2013-05-08 3 views
0

PHP 객체를 가지고 있습니다.이 객체에 대해 2 가지가 명확하고, 12 번 (1-12) 이상 반복 할 필요가 없습니다. 나는 또한 항상 한 번 이상 반복해야 할 것이다.PHP는 객체의 길이를 기준으로 출력을 처리합니다.

개체가 6 개 항목보다 길어서 6 개 항목보다 길어서 결과를 2 <ol> 개로 분할해야하고 내게 이렇게 좋은 방법을 알 수없는 경우 문제가 발생합니다. 여기

이 객체에서 6 개 이상의 항목이 있습니다 2 그래서 I 출력 2에 루프를 분할 할 수 있습니다 경우 어떻게 내 시도,
<?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; ?> 

지금 내 시도가 하나 개의 목록에있는 모든 결과를 표시한다 <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> 
관련 문제