php json-decode输出错误

时间:2014-09-04 23:11:44

标签: php json

我的php代码生成一个非有效的json输出错误

我的PHP代码:

$questions = array();
while($question = mysql_fetch_array($result, MYSQL_ASSOC)) {
$questions[] = array('question'=> $question);
}
print_r ($questions);

$newQuestions = array('questions' => array());

foreach($questions as $key => $question){
    $newQuestion = array(
            'question' => $question['question']['question'],
            'correct' => $question['question']['correct'],
            'answers' => array(
                    $question['question']['answer1'],
                    $question['question']['answer2'],
                    $question['question']['answer3'],
                    $question['question']['answer4']
                )
    );

    $newQuestions['questions'][] = $newQuestion;

}

$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);

echo '<br/><br/>';
echo $output;

表格字段:

Question :
correct  :
answer 1 :
answer 2 :
answer 3 :
answer 4 :

示例:

Question : is php a good language ?
correct  : 1
answer 1 : yes
answer 2 : no
answer 3 : maybe
answer 4 : good

输出正常,并按我想要的格式化。

输出样本:http://pastebin.com/eefS7KYW

我确信我的PHP代码是正确的,但我不知道究竟是什么问题!!

============== 修正:它只是两个echo $输出!

1 个答案:

答案 0 :(得分:1)

好像你正在做很多变量传递,很快就会变得很混乱。特别是当所有变量都是“问题”的迭代时。您似乎正在从数据库中提取的信息中创建一个数组,格式为[问题[问题,更正,答案[1,2,3,4]]]这种代码格式可能更好用吗?

   $newQuestions = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $newQuestions['questions'][] = array(
    'question'  =>  $row['question'],
    'correct'   =>  $row['correct'],
    'answers'   =>  array(
        $row['answer1'],
        $row['answer2'],
        $row['answer3'],
        $row['answer4']
        )
    );
}

    $output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);

    echo '<br/><br/>';
    echo $output;

在错误的地方有分号。修复上面的代码并使用以下代码测试代码:

<?php

$array = array(
    array('question'=>'Question1',
        'correct'=>3,
        'answer1' => 'Q1Answer1',
        'answer2' => 'Q1Answer2',
        'answer3' => 'Q1Answer3',
        'answer4' => 'Q1Answer4'
    ),
    array('question'=>'Question2',
        'correct'=>3,
        'answer1' => 'Q2Answer1',
        'answer2' => 'Q2Answer2',
        'answer3' => 'Q2Answer3',
        'answer4' => 'Q1Answer4'
    ),
    array('question'=>'Question3',
        'correct'=>3,
        'answer1' => 'Q3Answer1',
        'answer2' => 'Q3Answer2',
        'answer3' => 'Q3Answer3',
        'answer4' => 'Q1Answer4'
    )
);

$newQuestions = array();
//while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($array as $row){
    $newQuestions['questions'][] = array(
    'question'  =>  $row['question'],
    'correct'   =>  $row['correct'],
    'answers'   =>  array(
        $row['answer1'],
        $row['answer2'],
        $row['answer3'],
        $row['answer4']
        )
    );
}

print_r($newQuestions);
$output = json_encode(($newQuestions),JSON_UNESCAPED_UNICODE);

echo '<br/><br/>';
echo $output;

?>