php - 如果数据库中的值等于字符串,则将数组添加到嵌套 JSON
问题描述
我的数据库中有多个表,我想将它们连接在一起以为 GET 请求创建嵌套的 JSON。有一次,我想根据数据库中的值添加一个数组,例如(type === "fixValue")。
... $sql = "SELECT name, type
FROM section INNER JOIN question ON section.section_id = question.section_id
WHERE question.section_id = ".$row_section['section_id']."";
$stmtq = $db->query($sqlq);
$stmtq -> execute();
while( $row_question = $stmtq->fetch(PDO::FETCH_ASSOC)){
$question_array['name'] = $row_question['name'];
$question_array['type'] = $row_question['type'];
if($row_question['type'] == "fixValue"){
$question_array['options'] = array();
}
array_push($section_array['sectionQuestion'], $question_array);
} ....
我的 json 输出现在是:
{
"name": "Test",
"something": "Test",
"array1": [
{
"name": "Section",
"array2": [
{
"name": "Something",
"type": "fixValue",
"options": []
},
{
"name": "Sometthing2",
"type": "notFixValue",
"options": []
}
]
}
]}
我想要的输出:
{
"name": "Test",
"something": "Test",
"array1": [
{
"name": "Section",
"array2": [
{
"name": "Something",
"type": "fixValue",
"options": []
},
{
"name": "Sometthing2",
"type": "notFixValue",
}
]
}
]}
因此,选项数组不仅被添加到值为“fixValue”的项目中。具有与“fixValue”不同类型值的项目应该没有“options”数组。任何想法如何实现这样的目标?
解决方案
尝试使用计数器而不是 array_push:
... $sql = "SELECT name, type
FROM section INNER JOIN question ON section.section_id = question.section_id
WHERE question.section_id = ".$row_section['section_id']."";
$stmtq = $db->query($sqlq);
$stmtq -> execute();
$cnt = 0;
while( $row_question = $stmtq->fetch(PDO::FETCH_ASSOC)){
$question_array['name'] = $row_question['name'];
$question_array['type'] = $row_question['type'];
if($row_question['type'] == "fixValue"){
$question_array['options'] = array();
}
$section_array['sectionQuestion'][$cnt] = $question_array;
unset($question_array);
$cnt++;
} ....
推荐阅读
- javascript - 保存上下文
- javascript - React-dates 如何识别用户选择数据的方式
- javascript - css关键帧动画反转
- java - 某些曲线的 Java 区域构造函数挂起
- google-apps-script - 在 Google Apps 脚本中获取用户 ID
- jquery - 如何在打印时间的中心做数据表标题..?
- machine-learning - 强化学习:处理不可量化的反馈系统
- python - 使用opencv python通过鼠标拖动调整图像大小
- ubuntu - 不使用 sudo 运行 Pyspark
- codeigniter - Codeigniter 3 - 查询生成器“加入”方法问题 - 记录重复