0

suppose I have a mysql table like following:

     id value
     1   01
     2   03
     3   02
     4   15
     5   05
     6   04
     7   06
     8   10
     9   07
     10  09
     11  08
     12  11
     13  12
     14  14
     15  13
     16  16

How can I convert them to a string like this:

  01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16

any help will be greatly appreciated, thanks!

3
  • What are the rules here? Just get all rows from the table, and insert | after every 4th row (except the last set)? Commented Jan 9, 2012 at 8:10
  • Do you want to make the conversion in php or mysql? Commented Jan 9, 2012 at 8:14
  • yes, using php, you are right Commented Jan 9, 2012 at 8:15

2 Answers 2

1
$result = "SELECT value FROM `your_table` ORDER BY id ASC";

$i = 0;
$string = '';
while($row = mysql_fetch_assoc($result)){
   $i++;
    $string += $row['value'].',';
   if($i % 4 == 0){
     $string = substr_replace($string, '|',strlen($string) - 1, 1); 
   }    
}

$string = substr($string, 0, strlen($string) - 1);
Sign up to request clarification or add additional context in comments.

Comments

0

In general you can always typecast a value to become a string:

$str = (string) $i["mysql_field"];

I think what you are looking is something like this (without knowing how your query is):

$counter = 0;
$result = "";
$sql = mysql_query(...);
while ($i = mysql_fetch_array($sql)){
    $result .= $i["value"];
    if ($counter == 3){
        $counter = 0;
        $result .= "|";
    }else{
        $result .= ",";
        $counter++;
    }
}

This will add the "|" character for every 4th iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.