2017-11-15 1 views
0

文字列値の配列を返すデータベースクエリがあります。私はそれらをコンマ区切りで別の文字列に追加したい。文字列でphp配列の値を追加すると出力が得られません

$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

クエリをテストして、期待した結果を返しましたか?私の見解では、少なくともMYSQLでは有効ではないようです。 –

+0

whileループ内でforeachを使用する必要はありません。また、[GROUP_CONCAT](https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group)もご覧ください。 -concat) – hassan

+0

@chade_:はい彼らは結果を出します。 – ragnar1992

答えて

0

あなたは($の場所として$場所)ラインのforeachを削除することができます

あなたは自分の場所を追加する必要がありますので、あなたの中には、すでに場所に[「name」を]すべての行をフェッチします。あなたのforeachのは、私はあなたが私はあなたの問題を理解していれば、あなたにExplode function in php

+0

ありがとうございます。 – ragnar1992

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; 
} 

希望します!

0

を助けるかもしれない機能を爆発を見てすべきだと思う文字列$場所に

+0

お試しいただきありがとうございます – ragnar1992

+0

お願いします。 – kunal

関連する問題