Mysql
 sql >> Base de données >  >> RDS >> Mysql

Créer un objet json imbriqué à l'aide de php mysql

Bonjour essayez ceci,

<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
    $sub_cat_id = $_GET['sub_cat_id']; 
    $result = mysql_query("SELECT * FROM $questions WHERE sub_cat='$sub_cat_id' ORDER BY level_fk ASC"); 
    $json_response = array(); //Create an array
    while ($row = mysql_fetch_array($result))
    {
        $row_array = array();
        $row_array['qus_pk'] = $row['qus_pk'];        
        $row_array['question'] = $row['question'];
        $row_array['answers'] = array();
        $qus_pk = $row['qus_pk'];  

        $option_qry = mysql_query("SELECT * FROM $qus_ans WHERE qus_pk=$qus_pk");
        while ($opt_fet = mysql_fetch_array($option_qry))
        {
            $row_array['answers'][] = array(
                'options' => $opt_fet['options'],
                'right_ans' => $opt_fet['right_ans'],
            );

        }
        array_push($json_response, $row_array); //push the values in the array
    }
    echo json_encode($json_response);
}
?>