Home  >  Article  >  Backend Development  >  php怎么格式化字符串

php怎么格式化字符串

WBOY
WBOYOriginal
2016-06-13 10:34:481230browse

php如何格式化字符串
有数据库字段如下:
name sum
张三 20
李四 30
王五 11
麻子 12

想从数据库读出数据并格式化成以下格式:
var myData =new Array(['张三',20],['李四',30],['王五',11],['麻子',12]);

在C#里面有format 和stringbuilder函数很容易实现,不知道在PHP里面有类似的函数吗,欢迎贴代码

------解决方案--------------------

PHP code
$data = array(    array('张三', 20),    array('李四', 30),    array('王五', 11),    array('麻子', 12));$str = '';foreach ($data as $arr) {    $str .= ",['{$arr[0]}', {$arr[1]}]";}//echo ltrim($str, ',');// ['张三', 20],['李四', 30],['王五', 11],['麻子', 12]$myData = "var myData =new Array($str);";//echo $myData;// var myData =new Array(,['张三', 20],['李四', 30],['王五', 11],['麻子', 12]);<br><font color="#e78608">------解决方案--------------------</font><br>直接json_encode($mydate);就好了,就是json格式的<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
$data = array(    array('张三', 20),    array('李四', 30),    array('王五', 11),    array('麻子', 12));echo json_encode($data);<div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP 5.4.5 公布Next article:php操控nginx解决方法