php - 如果数据库中的值等于字符串,则将数组添加到嵌套的 JSON

标签 php mysql pdo

我的数据库中有多个表,我想将它们连接在一起,为 GET 请求创建一个嵌套的 JSON。有一次我想根据数据库中的值添加一个数组,例如(类型 === "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++;
            } ....

关于php - 如果数据库中的值等于字符串,则将数组添加到嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662397/

相关文章:

php - 使用 PDO 在一个表中查找记录并将数据追加到另一个表中

php - 我可以在 PHP 中混合使用 MySQL API 吗?

php - If 语句给出错误答案

mysql使用if和case语句生成

mysql - 通过在一个简单的表上使用 MySql 进行三次计数和分组......是否可以在一个查询中进行?

php - PDO MYSQL 更新不工作

PHP PDO GO 附近语法不正确,MSSQL 到 sqlsrv

php - 使用ajax、mysql、php显示数据库中的数据

php - 时间(); 2038年之后?

Mysql 5.7 性能调优。存储过程响应时间过长