PHP根据对象长度循环遍历对象操作输出


PHP looping over object manipulate output based on object length

我有一个PHP对象,我要循环,我知道这个对象定义了两个东西,我永远不需要循环超过12次(1-12),我也必须至少循环一次。

当对象超过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个项目?

试试这个:

<?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>