【问题标题】:PHP looping over object manipulate output based on object lengthPHP循环对象根据对象长度操作输出
【发布时间】:2013-05-02 22:43:47
【问题描述】:

我有一个要循环的 PHP 对象,我知道这个对象有 2 件事是确定的,我永远不需要循环超过 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 &lt;div class="col_1"&gt;,每个列表包含 6 个项目?

【问题讨论】:

    标签: php loops object foreach


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2021-11-14
      • 2015-02-23
      相关资源
      最近更新 更多