我有以下返回的查询:
"Code1""Code2""Code3"
我需要的是结果是这样的CSV格式:
'Code1','Code2','Code3'
如何修改代码才能完成此操作?
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata = ($row['code']);
echo json_encode($mydata);
}
$result->free();
$conn->close();
?>
答案 0 :(得分:2)
每次迭代都应该推送到数组。构建阵列后,您可以将其转换为json并回显它。
$mydata = array();
while ($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$json = json_encode($mydata);
$string = str_replace(array('[', ']'), '', $json);
echo $string;
答案 1 :(得分:1)
试试这个
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$result->free();
$conn->close();
echo "'".implode("','",$mydata)."'";
?>
或者您需要json_encode? p>