2017-02-01 68 views
1

我想要thisthis得到JSON輸出。不幸的是,json_encode()函數不會將數組編碼爲該格式。根本沒有任何回報。這裏是我的代碼。'php JSON_encode不起作用

$output = array(
    'responseData' => array(), 
    'responseDetails' => null, 
    'responseStatus' => 200 
); 

$x = 0; 
while ($row = mysqli_fetch_assoc($result)) { 
    foreach ($row as $k => $v) { 
     $output['responseData']['result'][$x][$k] = $v; 
    } 
    $x++; 
} 

print_r($output); 
header('Content-Type: application/json'); 
echo json_encode($output , JSON_FORCE_OBJECT); 

我找不到原因。有人請幫我找到解決方案。

編輯:對不起。這裏是輸出 -

預期JSON輸出 -

{ 
"responseData": { 
    "results": [{ 
     "qid": 1, 
     "qtitle": "When do we finish this project ?", 
     "qimage_url": "http://www.wearesliit.com/example.png", 
     "user": "samith", 
     "date": "2016-01-01T02:15:12.356Z", 
     "type": 1, 
     "category": 5, 
     "tags": ["common_senese", "truth", "bazsa_awsanna"], 
     "note": "Sample quetion" 
    }, {}, {}] 
}, 
"responseDetails": null, 
"responseStatus": 200 } 

我沒有得到任何JSON輸出的。但這裏是數組的print_r結果。

Array(
[responseData] => Array 
    (
     [result] => Array 
      (
       [0] => Array 
        (
         [question_ID] => 1 
         [question_Title] => Which shape does not belong with the other three shapes? 
         [question_Image_URL] => http://www.wearesliit.com/images/quiz/questions/1.jpg 
         [quetion_Note] => Easy IQ question. 
         [category_ID] => 7 
         [username] => samith 
         [added] => 2017-01-29 21:50:52 
        ) 

       [1] => Array 
        (
         [question_ID] => 2 
         [question_Title] => Tim earns $10 per hour at his job. When he gets paid on Friday, he is paid for 40 hours of work. He then goes out and spends 10% of his earnings on entertainment that weekend. How much money is he left with on Monday? 
         [question_Image_URL] => 
         [quetion_Note] => Easy IQ question. 
         [category_ID] => 7 
         [username] => samith 
         [added] => 2017-01-29 21:50:52 
        ) 
      ) 

    ) 

[responseDetails] => 
[responseStatus] => 200) 
+0

什麼JSON輸出?在你的問題中包括它在內? – Kaylined

+0

@安南第二個鏈接,只有,我猜。 –

+0

由於它在代碼中顯示'print_r($ output);'的結果。 – AbraCadaver

回答

0

除去

header('Content-Type: application/json'); 

記住,報頭被髮送的任何實際的輸出()之前必須被調用,或者通過正常的HTML標記,在一個文件中的空行,或從PHP。使用include或require函數或其他文件訪問函數讀取代碼,並在調用header()之前輸出空格或空行是非常常見的錯誤。使用單個PHP/HTML文件時存在同樣的問題。

JSON_FORCE_OBJECT

echo json_encode($output , JSON_FORCE_OBJECT);