RE: extract varying data from array with different formatting

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

 



On 14 April 2009 18:12, PJ advised:

> Jim Lucas wrote:
>> PJ wrote:
>>> Jim Lucas wrote:
>>>> PJ wrote:
>>>>> foreach does a nice job if you want the results identical each
time.
>>>>> What can you use to change the formatting of the results dependent
on
>>>>> the number of results. Here's an example:
>>>>> foreach ( $authors[$bookID] AS $authorID => $authorData ) {

>>>>>                 # Display the echo "{$authorData['first_name']}
>>>>> {$authorData['last_name']}\n";
>>>>>             }
>>>>> 
>>>>> will echo - Joe Boe John Blue Andy Candy etc depending on how many
>>>>> rows we have.
>>>>> What I want is: Joe Boe, John Blue, Andy Candy & Hans Stick (
>>>>> separated by commas, except for the last one which is separated
with
>>>>> & . I thought of passing a variable to the foreach and then using
if
>>>>> elseif... but that can't work because the variable is reset to 0
>>>>> after each pass. Can't get switch to do it (maybe I don't
understand
>>>>> it right. Help ? 

Needing effectively a three-way flag, I think I'd think a bit outside
the
box and go with something like (untested, but the general principle is
right!):

    $count = FALSE;
    foreach ($authors[$bookID] as $authorID=>$authorData):
       if ($count===FALSE):
          $count = count($authors[$bookID])-1;
       elseif (--$count):
          echo ', ';
       else:
          echo ' & ';
       endif;
       echo $authorData['first_name'], ' ', $authorData['last_name'];
    endforeach;

Cheers!

Mike

 --
Mike Ford,  Electronic Information Developer,
C507, Leeds Metropolitan University, Civic Quarter Campus, 
Woodhouse Lane, LEEDS,  LS1 3HE,  United Kingdom
Email: m.ford@xxxxxxxxxxxxxx
Tel: +44 113 812 4730


To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm

-- 
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