Php 如何使json_encode始终作为json数组返回?
这是我的代码:Php 如何使json_encode始终作为json数组返回?,php,arrays,json,multidimensional-array,slim,Php,Arrays,Json,Multidimensional Array,Slim,这是我的代码: $db = connect_mysqli(); $response = array(); $sql = "SELECT * FROM questions ORDER BY RAND ()"; $result = $db->query($sql); while($row = $result->fetch_array(MYSQL_ASSOC)) { $response['answers'][$row['id']] = array('q
$db = connect_mysqli();
$response = array();
$sql = "SELECT * FROM questions ORDER BY RAND ()";
$result = $db->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC))
{
$response['answers'][$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);
}
echo json_encode($response);
以下是回应:
{
answers: {
1: {
question_id: "1",
option_id: null
},
2: {
question_id: "2",
option_id: null
},
3: {
question_id: "3",
option_id: null
},
4: {
question_id: "4",
option_id: null
}
}
}
如何使响应始终返回JSON数组?不是像那样的JSON对象。有时,响应是返回JSON数组,在某些情况下是返回JSON对象。我希望所有响应都是JSON数组
所以,应该是这样的:
{
answers: [
1: {
question_id: "1",
option_id: null
},
2: {
question_id: "2",
option_id: null
},
3: {
question_id: "3",
option_id: null
},
4: {
question_id: "4",
option_id: null
}
]
}
这对你有帮助吗
$response = json_encode($response);
前一行应更改为:
$response['answers'][] = array('question_id'=>$row['id'], 'option_id'=>null);
问题的根源在于,数组的起始索引不是0。将
$row['id']
转换为字符串以获得所需的结果
$db = connect_mysqli();
$response = array();
$sql = "SELECT * FROM questions ORDER BY RAND ()";
$result = $db->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC))
{
$response['answers'][(string)$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);
}
echo json_encode($response);
尝试将
$response['answers'][$row['id']]]
更改为$response['answers'][/code>我需要它作为一个键$response['answers'][$row['id']]@MrHeryThen然后尝试从数据库中获取一个对象,而不是数组。如果您需要该键为$row['id'],那么您得到的json输出是正确的。在json中不能有键作为值的数组。如果你想让它返回一个数组,那么将id嵌入到对象中。我需要这个$response['answers'][$row['id']]作为一个键如果你需要一个键,它是一个对象,而不是数组,你需要它。数组总是从零索引开始,然后从零索引开始。嗯,那我怎么能显示它呢?if是一个JSON数组回答[1]。option_id,JSON对象如何访问?这是如何将其作为对象而不是数组进行访问:$answers[1]->option_id
在JavaScript中访问数组或对象是相同的表示法:answers[1]。option_id
应该可以工作。看到这个:不,它仍然和以前一样:(@DimasAdiAndrea请验证您期望的json。
$db = connect_mysqli();
$response = array();
$sql = "SELECT * FROM questions ORDER BY RAND ()";
$result = $db->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC))
{
$response['answers'][(string)$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);
}
echo json_encode($response);