使用 php mysql 创建嵌套的 json 对象

Posted

技术标签:

【中文标题】使用 php mysql 创建嵌套的 json 对象【英文标题】:Create nested json object using php mysql 【发布时间】:2015-07-21 05:21:26 【问题描述】:

我有两个表,表 1 有 2 个字段(question_pk、question_name),表 2 有 4 个字段(ans_pk、options、question_fk 和 right_answer)。 我想创建如下结构的json


    "type": "quiz",
    "name": "Brand Colors",
    "description": "Can you identify these brands by the background color?",
    "questions": [
        
            "name": "Can you identify this color?",
            "description": "#ea4c89",
            "answers": [
                
                    "name": "Dribbble",
                    "description": "dribbble.png",
                    "weight": 1
                ,
                
                    "name": "Amazon",
                    "description": "amazon.png",
                    "weight": 0
                ,
                
                    "name": "Apple",
                    "description": "apple.png",
                    "weight": 0
                
            ]
        ,
        
            "name": "Can you identify this color?",
            "description": "#3d9ae8",
            "answers": [
                
                    "name": "Youtube",
                    "description": "youtube.png",
                    "weight": 0
                ,
                
                    "name": "Dropbox",
                    "description": "dropbox.png",
                    "weight": 1
                ,
                
                    "name": "Wordpress",
                    "description": "wordpress.png",
                    "weight": 0
                
            ]
        ,
        
            "name": "Can you identify this color?",
            "description": "#c4302b",
            "answers": [
                
                    "name": "Youtube",
                    "description": "youtube.png",
                    "weight": 1
                ,
                
                    "name": "Twitter",
                    "description": "twitter.png",
                    "weight": 0
                ,
                
                    "name": "Vimeo",
                    "description": "vimeo.png",
                    "weight": 0
                
            ]
        

    ]

我的 php 代码

<?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
        $i=1;
                        while ($row = mysql_fetch_array($result))
                        
                        $row_array['qus_pk'] = $row['qus_pk'];        
                        $row_array['question'] = $row['question'];
                        $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['options'] = $opt_fet['options'];  
                        $row_array['right_ans'] = $opt_fet['right_ans'];  
                        array_push($json_response,$row_array); //push the values in the array
                                                   


                        $i++;
                        
        echo json_encode($json_response);


?>

而我的结果我得到如下 json 响应

[
    
        "qus_pk": "1",
        "question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
        "options": "45",
        "right_ans": "0"
    ,
    
        "qus_pk": "1",
        "question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
        "options": "40",
        "right_ans": "0"
    ,
    
        "qus_pk": "1",
        "question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
        "options": "35",
        "right_ans": "1"
    ,
    
        "qus_pk": "1",
        "question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
        "options": "50",
        "right_ans": "0"
    ,
    
        "qus_pk": "2",
        "question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
        "options": "4 times",
        "right_ans": "0"
    ,
    
        "qus_pk": "2",
        "question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
        "options": "1 times",
        "right_ans": "0"
    ,
    
        "qus_pk": "2",
        "question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
        "options": "3 times",
        "right_ans": "1"
    ,
    
        "qus_pk": "2",
        "question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
        "options": "5 times",
        "right_ans": "0"
    
]

在我每次重复问题时的回答中,如何避免和如果我想获得第一个 json 结构, 在我的 PHP 代码中我需要在哪里进行更改?如果有人知道帮助我。

【问题讨论】:

【参考方案1】:

你好,试试这个,

<?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);

?>    

【讨论】:

谁能给出运行此代码的表结构?我们可以用它来构建 D3 树 json 吗??【参考方案2】:

我认为这段代码更容易理解,而且它使用 mysqli 的方式...

这是基于我自己的数据结构,我在做某事,我没有时间上午。使其适应问题,但应该很容易弄清楚如何使其适应其他结构:

$usersList_array =array();
$user_array = array();
$note_array = array();

$fetch_users = mysqli_query($mysqli, "SELECT 
        ID, 
        Surname, 
        Name 
    FROM tb_Users 
    WHERE Name LIKE 'G%' 
    ORDER BY ID") or die(mysqli_error($mysqli));
while ($row_users = mysqli_fetch_assoc($fetch_users)) 
    $user_array['id'] = $row_users['ID'];
    $user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
    $user_array['notes'] = array();

    $fetch_notes = mysqli_query($mysqli, "SELECT 
        id, 
        dateIns, 
        type, 
        content 
     FROM tb_Notes 
     WHERE fk_RefTable = 'tb_Users' AND 
         fk_RefID = ".$row_users['ID'].""
   ) or die(mysqli_error($mysqli));
    while ($row_notes = mysqli_fetch_assoc($fetch_notes)) 
        $note_array['id']=$row_notes['id'];
        $note_array['dateIns']=$row_notes['dateIns'];
        $note_array['type']=$row_notes['type'];
        $note_array['content']=$row_notes['content'];
        array_push($user_array['notes'],$note_array);
    

    array_push($usersList_array,$user_array);


$jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);


echo $jsonData; 

生成的 JSON:

[

    "id": "1",
    "surnameName": "Xyz Giorgio",
    "notes": [
        
            "id": "1",
            "dateIns": "2016-05-01 03:10:45",
            "type": "warning",
            "content": "warning test"
        ,
        
            "id": "2",
            "dateIns": "2016-05-18 20:51:32",
            "type": "error",
            "content": "error test"
        ,
        
            "id": "3",
            "dateIns": "2016-05-18 20:53:00",
            "type": "info",
            "content": "info test"
        
    ]
,

    "id": "2",
    "cognomeNome": "Xyz Georg",
    "notes": [
        
            "id": "4",
            "dateIns": "2016-05-20 14:38:20",
            "type": "warning",
            "content": "georg warning"
        ,
        
            "id": "5",
            "dateIns": "2016-05-20 14:38:20",
            "type": "info",
            "content": "georg info"
        
    ]

]

【讨论】:

欢迎来到 Stack Overflow。虽然您提供的链接可能会回答问题,但最好将解决方案的基本部分直接放在您的答案中,以防链接上的页面将来消失。 谢谢,我认为避免重复是首选。我会输入我的代码:-)【参考方案3】:

一个将表格嵌套到 php 数组中的基本类。

PHP 类

// chain data into a php array, filtering by relation to parent, based on a structure definition array
// nest child data by relation to parent data
// assign a array label "arr_label" to child definition to define what key the filtered data will use 
// assign a parent key "p_key" and a child key "c_key" to child definition to assign connection points from child to parent
// load array data to filter into "arr" key on child definition

class class_chain_filter

    var $return_arr;
    
    function __construct()
    
     // CONSTRUCTOR
    
    // input a defined filter tree array and output a processed result
    function chain_filter($filter_tree)
    
        // can feed either a single record a set of rows...
        if(!$this->is_assoc($filter_tree['arr']))
            $this->return_arr = $filter_tree['arr']; // root for return array
        else
            $this->return_arr[] = $filter_tree['arr']; // force a numeric array so return is consistent.
            
        $this->do_chain_filter( $filter_tree['next_arrs'], $this->return_arr );
        
        return $this->return_arr;
     // $this->chain_filter($filter_tree) // public
    
    
    function is_assoc($arr)
    
        return array_keys($arr) !== range(0, count($arr) - 1);
    

    
    function do_chain_filter(&$tree_arr, &$final_arr)
    
        $cur_final_node = &$final_arr;
        
        if( !is_array($cur_final_node) )
            return false;
        
        // send the next_arrs
        foreach($final_arr as $f_key => $f_arr)
        
            $cur_final_node = &$final_arr[$f_key];
            
            foreach($tree_arr as $n_key => $n_arr)
            
                $cur_tree_node = $tree_arr[$n_key];
                // $final_cur_el['arr_label'] = 'true';
                $next_final_node = &$cur_final_node[$cur_tree_node['arr_label']];
                
                // data up hombre 
                // filter out array elements not related to parent array
                $result = $this->children_of_parent(
                    $cur_final_node, 
                    $cur_tree_node['arr'], 
                    $cur_tree_node['p_key'], 
                    $cur_tree_node['c_key']
                );

                $next_final_node = $result;

            
                // now recurse if we have more depths to travel...
                if(!empty($cur_tree_node['next_arrs']))
                    $this->do_chain_filter($cur_tree_node['next_arrs'], $next_final_node);

            
        
     // this->function chain_filter(&$tree_arr, &$final_arr)




    // take 2 arrays
    // first array is an associative array. 
    // second array is an array of associative arrays.
    // return children of second array that belong to parent array
    function children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
    
        // parent   = a record
        // child    = multiple records
        // filter out children that don't apply to parent.
        // return the result
        $parent_id = $arr_parent[$key_parent];
        
        foreach($arr_children as $arr_child)
        
            $child_id = $arr_child[$key_child];
            
            if($child_id == $parent_id)
                $return_arr[] = $arr_child;
        
        
        if(!empty($return_arr))
            return $return_arr;
     // this->children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )


 // end. class class_chain_filter

加载一些表(使用您自己的首选数据库类)

$areas = $db->get("SELECT * FROM areas");
$rooms = $db->get("SELECT * FROM rooms");
$exits = $db->get("SELECT * FROM exits");

定义我们返回的数组树结构

// predefine tree structure for generation
// structure definition array example...
$tree_arr = array (

    "arr"   => $areas, // root (can be multiple rows or a single record)
    
    "next_arrs" => array ( // children
    
        0 => array(
        
            "arr"           => $rooms,          // array to filter against parent
            "arr_label"     => "rooms",         // for the php array label
            "p_key"         => "id",            // field name of parent // eg) id
            "c_key"         => "areaid",        // this array's field name that links it to parent

            "next_arrs" => array( // children

                0 => array(
                
                    "arr"           => $exits,              // array to filter against parent
                    "arr_label"     => "exits",             // for the php array label
                    "p_key"         => "id",                // field name of parent / blank if root / eg) id
                    "c_key"         => "roomid"             // this array's field name that links it to parent
                )
            )
        )
    )

); // $tree_arr

现在将对象和进程创建到目标数组中

$c = new class_chain_filter();
$return_arr = $c->chain_filter($tree_arr);
print_r($return_arr);

...输出应该看起来像...

Array (
[0] => Array
    (
        [id] => 1
        [name] => New World
        [author] => anon
        [resetfreq] => 3
        [rooms] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [areaid] => 1
                        [name] => Entrance
                        [description] =>  The air is humid here.
                        [exits] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 1
                                        [roomid] => 1
                                        [toroomid] => 2
                                        [direction] => n
                                        [description] => A Hall
                                        [keyid] => 1
                                    )

                                [1] => Array
                                    (
                                        [id] => 5
                                        [roomid] => 1
                                        [toroomid] => 3
                                        [direction] => s
                                        [description] => Entrance 
                                        [keyid] => 
                                    )

                            )

                    )

                [1] => Array
                    (
                        [id] => 2
                        [areaid] => 1
                        [name] => A Corridor
                        [description] => Seems nothing is really going on in this room. Bland tapestry and nothing worth really hanging around for. From the west comes the sound of people training. To the east you can hear people practicing skills and abilities.
                        [exits] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 2
                                        [roomid] => 2
                                        [toroomid] => 1
                                        [direction] => s
                                        [description] => A Corridor
                                        [keyid] => 
                                    )

                                [1] => Array
                                    (
                                        [id] => 7
                                        [roomid] => 2
                                        [toroomid] => 4
                                        [direction] => e
                                        [description] => Practice Room
                                        [keyid] => 
                                    )

                                [2] => Array
                                    (
                                        [id] => 9
                                        [roomid] => 2
                                        [toroomid] => 5
                                        [direction] => w
                                        [description] => Training Room
                                        [keyid] => 
                                    )

                                [3] => Array
                                    (
                                        [id] => 11
                                        [roomid] => 2
                                        [toroomid] => 8
                                        [direction] => n
                                        [description] => A Bend
                                        [keyid] => 
                                    )

                            )

                    )
            )
    )

)

然后你可以json_encode 数组将它从 PHP 数组转换为 JSON 字符串

【讨论】:

以上是关于使用 php mysql 创建嵌套的 json 对象的主要内容,如果未能解决你的问题,请参考以下文章

使用 php mysql 创建嵌套 json

如何使用 PHP 和 MySQL 创建 JSON 嵌套子父树(PDO 方法)

PHP/MySQL - JSON 中的嵌套组

如何使用 Spring boot 和 MYSQL 为多级菜单列表创建嵌套 JSON?

如何使用 laravel 或 mysql 创建嵌套的 json?

如何使用 mysql 本机 json 函数生成嵌套的 json 对象?