我有数据库查询,它返回一个字符串值数组。我希望它们以逗号分隔并附加到另一个字符串。
$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
$insert = "";
while($locations = $result1->fetch_assoc()) {
foreach ($locations as $location) {
$insert .= $location['name'] . ",";
}
}
$insert = rtrim($insert, ",");
}
$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
echo json_encode($response);
}
}
此$ insert数组未提供预期结果。它只给出“N”。
答案 0 :(得分:0)
您可以删除foreach行($ locations as $ location)
您已经将所有行提取到位置,因此您只需附加位置['name']。您的foreach已检索字符串$ locations
中的每个字符答案 1 :(得分:0)
我认为你应该看看可能对你有帮助的爆炸功能Explode function in php
答案 2 :(得分:0)
如果我理解你的问题。你需要使用php的implode()函数。试试这个: -
if ($result1->num_rows > 0) {
$ImplodeArray =array();
while($locations = $result1->fetch_assoc()) {
foreach ($locations as $location) {
$ImplodeArray[] = $location['name'];
}
}
$insert = implode(',',$ImplodeArray);
echo $insert;
}
希望它有所帮助!