Younis Ch
Younis Ch

Reputation: 11

converting comma separated string to a list

I am geeting the results like ali,aliiii,asd by echoing $row['GROUP_CONCAT(mem_name)'];.

How can I echo them like a list so that I can add anchor tag on click functions etc.i have the query

$sql=mysql_query("
    SELECT cat_id, GROUP_CONCAT(mem_name)  
    FROM o_newcatmem GROUP BY cat_id
");

I want the resuts to b displayed like this:

ali
aliiii
asd

Upvotes: 1

Views: 2044

Answers (3)

Baba
Baba

Reputation: 95101

You have a $string like this

$string = "ali,aliiii,asd";
echo "<pre>";

You have three options:

  1. You can use str_getcsv to convert CSV string to array

    $list = str_getcsv($string);
    foreach ( $list as $var ) {
        echo $var, "\n";
    }
    
  2. Convert them to array using explode

    $list = explode(",", $string);
    echo implode("\n", $list);
    
  3. Use just use str_replace

    $list = str_replace(",", "\n", $string);
    echo $list;
    

Upvotes: 2

Glavić
Glavić

Reputation: 43552

MySQL GROUP_CONCAT function has a SEPARATOR keywords.

  • You can use GROUP_CONCAT(mem_name SEPARATOR ',') AS mems_name in your SQL statement.
  • Use separator that does not exist in mem_name field.
  • Use alias AS mems_name, so your PHP code looks simple, like $row['mems_name'].

In your PHP just explode data by your separator $list = explode('|', $row['mems_name']);.

Upvotes: 1

Vikram Jain
Vikram Jain

Reputation: 5588

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Upvotes: 0

Related Questions