Re: extract varying data from array with different formatting

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

 



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 ?


your answer lies with not replacing foreach to make your life/output better. But with how the data is prepared and handed off to the foreach statement.

I am guessing that what you want would be something like this.

Since this looks like a snippet of code I sent you the other day, I will snag it "complete" from the other thread.

<?php

...

        # Test to see if the book has any authors
        if ( isset($authors[$bookID]) ) {

            # Tell us how many authors we found
            echo 'Found: ', count($author[$bookID]), ' authors';

            # Create an array that will hold the output from the DB.
            $aList = array();
            # Loop through the authors
            foreach ( $authors[$bookID] AS $authorID => $authorData ) {
                # Add all the authors to that new array
                 $aList[] = "{$authorData['last_name']}, {$authorData['first_name']}";
            }

            # Sanitize the output
            $aList = array_map('htmlspecialchars', $aList);

            # Get a count of how many authors their is.
            $tAuthors = count($aList);

            # If more then one, do...
            if ( $tAuthors > 1 ) {
                # Take the last one off, so we can handle it differently
                $last_author = array_pop($aList);
                echo join(', ', $aList), ' & ', $last_author;

            # If only one, then do...
            } elseif ( $tAuthors == 1 ) {
                echo join('', $aList);
            }
            echo '<br />';
        } else {
            echo 'No authors found';
        }


...

?>

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