代码:
while($row = mysqli_fetch_assoc($result))
{
$data[] = array(
'city' => $row["city"],
'hotel' => $row["hotel_name"]
);
}
mysqli_close($con);
$results = json_encode($data);
$json = json_decode($results, true);
foreach($json as $fet)
{
$datas = $fet['city']." | ".$fet['hotel'].", ";
echo $datas;
}
在这段代码中,我创建了一个自动完成文本框,我想在数据前后添加"
,我的数据如下所示:
delhi | Radisson, noida | Ramada Phuket Deevana Patong, noida | Eco Poplar
但是我想要这样:
"delhi | Radisson", "noida | Ramada Phuket Deevana Patong", "noida | Eco Poplar"
那么,我该怎么做? 谢谢
答案 0 :(得分:1)
只需将双引号放在单引号之间:'"'
改进:您可以在获取结果时保存格式化的字符串。 JSON相关功能没有用。然后使用implode()
$data = [];
while($row = mysqli_fetch_assoc($result))
{
// double quotes between single quotes
$data[] = '"' . $row["city"] . ' | ' . $row["hotel_name"] . '"';
}
mysqli_close($con);
// Here I removed useless json_encode/decode functions
// Then output strings separated by a coma
echo implode(', ', $data);
答案 1 :(得分:0)
在您的情况下,最后一个元素后会有逗号,请尝试以下代码:
$data = [];
foreach($json as $fet) {
$data[] = "\"{$fet['city']} | {$fet['hotel']}\"";
}
echo implode(", ", $data);
答案 2 :(得分:-2)
$data[] = array(
'city' => $row["city"],
'hotel' => $row["hotel_name"]
);
$results = json_encode($data);
$json = json_decode($results, true);
foreach($json as $fet)
{
$datas = '"'.$fet['city']." | ".$fet['hotel'].'"';
echo $datas;
}