I have a PHP object that I am looping over, I know 2 things are definate with this object, I will never need to loop more than 12 times (1-12) and I will also always have to loop at least once.
My problem comes when the object is longer than 6 items, as if it is longer than 6 items I need to split the results into 2 <ol>
and for the live of me I cannot figure out a nice way to do this?
Here is my attempt,
<?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; ?>
Now my attempt displays all the results in one list, how can if there are more than 6 items in the object, split the loop in 2 so that I output 2 <div class="col_1">
with a list of 6 items in each?
Try this:
<?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>
";
}
function wrapInOl($arrayOfLi)
{
$returnString = "<ol>
";
foreach ($arrayOfLi as $li)
{
$returnString .= $li;
}
return $returnString . "</ol>
";
}
/*
* The classname is adjustable, just in case
*/
function wrapInDiv($ol, $class)
{
return "<div class='$class'>
$ol</div>
";
}
?>
<!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>