简体   繁体   English

使用PHP将MySQL表数据转换为字符串

[英]convert mysql table data to string using php

suppose I have a mysql table like following: 假设我有一个如下的mysql表:

     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! 任何帮助将不胜感激,谢谢!

$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);

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. 每第4次迭代的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM