我无法弄清楚如何创建一个在数组内部有数组的Php json对象。我已经工作了好几个小时了,无法解决这个问题。我应该在while循环中使用oject并添加数组吗?
我想在我的问题数组中包含我的答案数组。
{
"success":true,
"total":2,
"question":[
{
"id":"1",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"1",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
"question":[
{
"id":"2",
"product":"The Product",
"question":"Some question here"
"answer":[
{
"answer_id":"1",
"answer":"First answer",
"is_correct":"0",
"question_id":"1"
},
{
"answer_id":"2",
"answer":"Second answer",
"is_correct":"1",
"question_id":"1"
}
]
}
],
见下面的代码。
$question_arr = array();
$answer_arr = array();
//Question table results
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row_question_array['id'] = $row['ID'];
$row_question_array['product'] = $row['product'];
$row_question_array['question'] = $row['question'];
array_push($question_arr,$row_question_array);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$row_anwser_array['answer_id'] = $row2['answer_id'];
$row_anwser_array['product'] = $row2['product'];
$row_anwser_array['answer'] = $row2['answer'];
$row_anwser_array['is_correct'] = $row2['is_correct'];
$row_anwser_array['question_id'] = $row2['question_id'];
array_push($answer_arr,$row_anwser_array);
}
}
} else {
echo "question 0 results";
}
$myObj->success = true;
$myObj->total = $result->num_rows;
$myObj->question = $question_arr;
$myObj->answer = $answer_arr;
//echo json_encode($question_arr);
//echo json_encode($answer_arr);
echo json_encode($myObj);
答案 0 :(得分:4)
无需创建两个单独的$question_arr
或$answer_arr
数组。相反,只需创建一个空结果数组$resultArr
并按以下方式重构代码,
$resultArr = array();
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array('success' => true, 'total' => $result->num_rows);
while($row = $result->fetch_assoc()) {
$resultArr['question'][$row['ID']] = array('id' => $row['ID'], 'product' => $row['product'], 'question' => $row['question']);
//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['question'][$row['ID']]['answer'][] = $row2;
}
}
$resultArr['question'] = array_values($resultArr['question']);
} else {
$resultArr = array('success' => false, 'total' => 0);
echo "question 0 results";
}
echo json_encode($resultArr);