loops - PHP looping over object manipulate output based on object length -
i have php object looping over, know 2 things definate object, never need loop more 12 times (1-12) , have loop @ least once.
my problem comes when object longer 6 items, if longer 6 items need split results 2 <ol>
, live of me cannot figure out nice way this?
here 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 $project) : ?> <li><a href=""><?php echo $project->project_name; ?></a></li> <?php $count ++; ?> <?php endforeach; ?> </ol> </div> <?php endif; ?>
now attempt displays results in 1 list, how can if there more 6 items in object, split loop in 2 output 2 <div class="col_1">
list of 6 items in each?
try this:
<?php //create object 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 $li) { $returnstring .= $li; } return $returnstring . "</ol>\n"; } /* * classname adjustable, 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 $project) { //fill array list-items $arrayofli[] = wrapinli($project->name); //six list-items? wrap if(count($arrayofli) === 6) { //wrap in unordered list $ol = wrapinol($arrayofli); //wrap in div , echo echo wrapindiv($ol, 'col_1'); //reset array $arrayofli = array(); } } ?> </body> </html>
Comments
Post a Comment