php—如果数据库中的值等于字符串,则向嵌套的json添加数组

ykejflvf  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(296)

我的数据库中有多个表,我想将它们连接在一起,为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",
            }
        ]
    }
]}

因此,options数组不仅被添加到值为“fixvalue”的项中。具有不同类型值(如“fixvalue”)的项不应包含“options”数组。你知道怎么做这样的事吗?

rkttyhzu

rkttyhzu1#

尝试使用counter而不是array\u 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++;
            } ....

相关问题