Forum Moderators: coopster

Message Too Old, No Replies

Multi-cell array

         

Folks

10:47 pm on Jul 14, 2009 (gmt 0)

10+ Year Member



Hi i have sorted array as:

$my_list = array('A','B','C','D','E','F','G','H','I','...');

and i want to output as menu from array to this(sorted by column):

A - D - G
B - E - H
C - F - I

and it should be easily change with some function variable to 2 column menu (it can be two standalone function also):
or beter aim i want change also how many(or max) rows will e in one column.

A - F
B - G
C - H
D - I
E

for better imagine its XHTML menu what looklike as:
(this is one column)


<ul class="sub_nav">
<li><a href="http://www.example.com/alpha/">Alpha</a></li>
<li><a href="http://www.example.com/issues/beta/">Beta</a></li>
<li><a href="http://www.example.com/issues/gamma/">Gamma</a></li>
<li><a href="http://www.example.com/issues/delta/">Delta</a></li>
<li><a href="http://www.example.com/issues/immigration/">Immigration</a></li>
<li><a href="www.example.com/issues/poverty/">Poverty</a></li>
<li><a href="www.example.com/issues/rural/">Rural</a></li>
<li><a href="www.example.com/issues/seniors_and_social_security/">Seniors and Social Security</a></li>
</ul>

Where UL is column and LI is row. in my array A,B,C,D..etc are sorted (<li></li>) tags

the most close what i get is this:


$my_list = array('A','B','C','D','E','F','G','H','I');
$cnt = 0;
$columns = array();
foreach($my_list as $list){
$column = ($cnt % 3) +1;
$columns[$column] .= '<li>'.$list.'</li>';
$cnt++;
}
echo '<ul class="sub_nav">'.$columns[1].'</ul>'.PHP_EOL;
echo '<ul class="sub_nav">'.$columns[2].'</ul>'.PHP_EOL;
echo '<ul class="sub_nav">'.$columns[3].'</ul>'.PHP_EOL;

but this gave me this result(sorted by row):

A - B - C
D - E - F
G - H - I

Many thanks if you know the solution im really confused.

coopster

2:07 am on Jul 15, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Something like this?
[webmasterworld.com...]

Folks

10:06 am on Jul 15, 2009 (gmt 0)

10+ Year Member



I dont know your example gave me an blank screen with no code, Cant anyone modify my code to sort by column not a sort by row?

Thanks im not too much familiar with PHP:)

coopster

1:00 pm on Jul 15, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I modified the code snippet from the link I offered slightly to adapt your array ...
$my_list = array('A','B','C','D','E','F','G','H','I'); 
$list = ''; // initialize
$n = array();
$numRows = count($my_list);
if ($numRows > 0) {
$columns = 3;
$numRows = ceil($numRows/$columns);
foreach ($my_list as $row) {
$nam = htmlentities($row);
$n[] = "<li>{$nam}</li>";
}
$n = array_chunk($n, $numRows);
foreach ($n as $rows) {
$list .= "\n<td>\n\t<ul>\n\t\t<li>" .
implode("</li>\n\t\t<li>", $rows) .
"</li>\n\t</ul>\n</td>\n"
;
}
}
print "<table><tr>$list</tr></table>";
exit;