Jump to content

Forming Columns


Disturbed One

Recommended Posts

Hello,

 

I have an array I want to put into three equal columns (each one starting with <ul> and ending with </ul>).

 

The array is dynamic, and can have anywhere from a few entries to 30.

 

$array = array(
'item1' => 'Item 1',
'item2' => 'Item 2',
'item3' => 'Item 3',
'item4' => 'Item 4',
'item5' => 'Item 5',
'item6' => 'Item 6',
'item7' => 'Item 7',
'item4' => 'Item 8',
'item5' => 'Item 9',
'item6' => 'Item 10',
'item7' => 'Item 11',
);

 

Should output

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<ul>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
<ul>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
</ul>

 

$array = array(
'item1' => 'Item 1',
'item2' => 'Item 2',
'item3' => 'Item 3',
'item4' => 'Item 4',
);

 

Should output

<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ul>
<li>Item 3</li>
</ul>
<ul>
<li>Item 4</li>
</ul>

 

And so on.

 

How can I accomplish this?

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/85865-forming-columns/
Share on other sites

try

<?php
$array = array('item1' => 'Item 1', 'item2' => 'Item 2', 'item3' => 'Item 3',
			'item4' => 'Item 4', 'item5' => 'Item 5', 'item6' => 'Item 6',
			'item7' => 'Item 7', 'item8' => 'Item 8', 'item9' => 'Item 9',
			'item10' => 'Item 10', 'item11' => 'Item 11');
$num_of_list = 3;
$total_item = count($array);
$ends = array(0);
while ($num_of_list > 0) {
$a = ceil($total_item / $num_of_list);
$ends[] = $a + max($ends);
$total_item -= $a;
$num_of_list--;
}
$i = 0;
foreach ($array as $item){
if (in_array($i, $ends)) echo "<ul>\n";
$i++;
echo "<li>$item</li>\n";
if (in_array($i, $ends)) echo "</ul>\n";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/85865-forming-columns/#findComment-438914
Share on other sites

Damn looks like someone beat me to it. This is what I managed to cook up anyway if you're interested:

 

<?php
$n = count($array);
$r = $n % 3;
$colsize = floor($n / 3);
$newcol = false;
$tmp = $colsize;
echo "<ul>\n";
foreach($array as $item) {
	if($tmp < 1) {
		if($r > 0 && $tmp > -1) $r--;
		else {
			$newcol = true;
			$tmp = $colsize;
		}
	} else $newcol = false;
	if($newcol) echo "</ul>\n<ul>\n";
	echo "\t<li>$item</li>\n";
	$tmp--;
}
echo '</ul>';
?>

 

Should work for any number of columns and array lengths, just change both the 3s up at the top to however many columns you need.

Link to comment
https://forums.phpfreaks.com/topic/85865-forming-columns/#findComment-439224
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.