Re: Looping through array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, November 16, 2006 3:14 pm, Ashley M. Kirchner wrote:
> Darrell Brogdon wrote:
>> So in other words, you have an array like $arr =
>> array(1,2,3,4,5,6,7,8,9,10) but you want it to render on the page
>> as:
>>
>>   5 4 3 2 1
>> 10 9 8 7 6
>>
>> right?
>     That would be correct.  James Tu provided a solution that I think
> will work.  I'm always open to other suggestions of course.

Any chance of just getting the stuff in the right order in the first
place?... :-)

If not, here is what I would do:

<?php
  $array = array(1,2,3,4,5,6,7,8,9,10);
  $array = array_reverse($array);
  $row_one = array_slice($array, 0, 5));
  $row_two = array_slice($array, 5));
?>
<table>
  <tr><td><?php echo implode("</td><td>", $row_one);?></td></tr>
  <tr><td><?php echo implode("</td><td>", $row_two);?></td></tr>
</table>

This would be fairly trivial to extend to multiple rows:

<?php
  //assume input $array in 'order' as above,
  //only with unknown length
  $array = array_reverse($array);
?>
<table>
</php
  for ($i = 0; $i < count($array); $i += 5){
    echo "  <tr><td>", implode("</td><td>", array_slice($array, $i,
5)), "</td></tr>\n";
  }
?>
</table>



YMMV

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux