SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast andygout's Avatar
    Join Date
    Jun 2012
    Location
    London, United Kingdom, United Kingdom
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Display array of links as string separated by commas using implode

    I知 trying to display an array of href links as a string with the results separated by commas so as to display:-
    I Am The Walrus, Hello, Goodbye, The Fool On The Hill, Magical Mystery Tour, Lady Madonna
    (NB: Some results will contain commas (Hello, Goodbye) so I値l need to use the 'implode' function rather than 'preg_replace').

    The links are comprised of three different values from each result, i.e. 'id' and 'url' for the URL and 'name' for the name to be displayed.

    My current code:
    Index:-
    PHP Code:
    <?php
    while ($row mysqli_fetch_array($result)) //Creates array.
    {
        
    $songs[] = array('id' => $row['id'], 'url' => $row['url'], 'name' => $row['name']);
    }
    ?>
    Display page:-
    PHP Code:
    <?php foreach ($songs as $song)
    {
    $song '<a href="/song/' $song['id'] . '/' $song['url'] . '">' $song['name'] . '</a>';
    }
    echo 
    implode(", "$songs);
    ?>
    Outputs:-
    Notice: Array to string conversion in C:\...
    Notice is repeated x 5 times (i.e. however many results there are)

    Followed by the below:-
    Array, Array, Array, Array, Array
    Again, repeated according to number of results.

    The method was taken from this problem: PHP Separate comma list with links, but it only requires the one value to create the link; mine needs three.

    I feel all I require to make this work is a minor tweak but I just can稚 figure it out any suggestions?

  2. #2
    SitePoint Zealot
    Join Date
    Feb 2012
    Location
    United Kingdom
    Posts
    113
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You're re-assigning the $song array variable to a new string value upon each iteration in the foreach loop; which will achieve nothing. You're then imploding the original $songs variable, which again will not work, because you have a multi-dimensional array, meaning that you're echoing out each sub-array (with the keys: id, url, and name).

    Try this:
    PHP Code:
    $songsList = array();

    foreach(
    $songs as $song) {
        
    $songsList[] = '<a href="/song/' $song['id'] . '/' $song['url'] . '">' $song['name'] . '</a>';
    }
    echo 
    implode(", "$songsList); 

  3. #3
    SitePoint Enthusiast andygout's Avatar
    Join Date
    Jun 2012
    Location
    London, United Kingdom, United Kingdom
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It works - thanks SO much!


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •