dongzhouhao4316
dongzhouhao4316
2016-05-22 15:02

json - 用逗号循环

已采纳

Problem Solved. Thanks everyone.

Code:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM movie WHERE status = 'In Cinemas' LIMIT 6";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

$moviename = $row['moviename'];
$cover = $row['poster'];

header('Content-Type: application/json; charset=utf-8');

$alldata [] = array('key'=>'movie-name', 'value'=>$moviename,'cover' =>$cover);
echo json_encode($alldata);

}}
else{

echo "does not work";
}

Result:

    { "items": 
[ 

{"key":"movie-name","value":"test","cover":"upload/movies/poster/1.png"}

{"key":"movie-name","value":"London","cover":"upload/movies/poster/2.png"}

]}

Problem:

no commas are separated the two outputs of json, that starts with {"key" - before the bracket should be the comma, please help to implement

Problem Solved. Thanks everyone.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dpd3982 dpd3982 5年前
    $sql = "SELECT * FROM movie WHERE status = 'In Cinemas' LIMIT 6";
    $result = $conn->query($sql);
    $master_array = array();
    
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
    $moviename = $row['moviename']; 
    $poster = $row['poster'];
    
    $master_array[] = array('key'=>'movie-name','value'=>$moviename,'cover'=>$poster);
    
    }
    header('Content-Type: application/json; charset=utf-8');
        echo json_encode($master_array);
    
    }
    else{
    
    echo "no";
    }
    
    点赞 评论 复制链接分享