Forum Moderators: coopster
I'm using the foreach function to do this.
foreach($my_list as &$list) echo "<li>".$list."</li>";
However, because I'm using columns, and I want to keep the alphabetical integrity of my information, I need to first reorder my array. See
So the $my_list array was like:
A B C D E F G H I
Because I'm using a three column layout, I need to reorder my data like:
A D G B E H C F I
How can I do this with PHP?
Thanks
[edited by: dreamcatcher at 8:03 am (utc) on Feb. 23, 2009]
[edit reason] No personal urls, thanks. [/edit]
IMO you should not need to reorder your data (as you still want to output it alphabetically), but instead control your layout. I don't think you can use a simple list to output your multiple columns as that would require a reorder of the data (as you suggest) - which would not make much sense if your list was viewed with a different stylesheet.
I would use either a series of 3 divs (populated sequentially/alphabetically), and float/position these into a 3 column layout (if viewed without a stylesheet they would appear one after the other - the correct order). Or perhaps even use a table if it could be perceived as tabular data?
$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 id="column1">'.$columns[1].'</ul>'.PHP_EOL;
echo '<ul id="column2">'.$columns[2].'</ul>'.PHP_EOL;
echo '<ul id="column3">'.$columns[3].'</ul>'.PHP_EOL;
A - B - C
D - E - F
G - H - I
Which could be achieved by styling a single list (floating the LI's of an appropriate width to create however many columns you wanted). I had assumed the OP was after:
A - D - G
B - E - H
C - F - I
$my_list=array('A','B','C','D','E','F','G','H','I');
$cnt = 0;
$list_a=array();
$list_b=array();
$list_c=array();
foreach($my_list as $list){
$column=($cnt%3)+1;
if($column==1) array_push($list_a,$list);
elseif($column==2) array_push($list_b,$list);
elseif($column==3) array_push($list_c,$list);
$cnt++;}
$my_list=array_merge($list_a,$list_b,$list_c);
print_r($my_list);
However, because I'm using columns, and I want to keep the alphabetical integrity of my information, I need to first reorder my array.
Unfortunately this method does not keep the 'alphabetical integrity of your information'. You have effectively reordered it A,D,G,B,... so it might look OK when viewed using your stylesheet on a regular browser, but accessibility wise it is no longer... accessible (if you are outputting it as a regular list as you suggest in your OP).