【问题标题】:Read nested json display each key value [From mySQL]读取嵌套 json 显示每个键值 [来自 mySQL]
【发布时间】:2020-04-07 09:05:05
【问题描述】:

我正在尝试读取嵌套的 JSON 数据,其中键值是子嵌套的键和值,但它似乎不起作用。 数据库表中的第一个 json 数据 [列:角色]

$json = array();
$sql = $db->query("SELECT * FROM u_info WHERE bid=".$branch);
while ($rs = $sql->fetch_assoc()) {    
    $rs['img'] = getImg($rs['img']);
    $query = $db->query('SELECT roles FROM wp_roles WHERE userid='.$rs['id'])->fetch_assoc();
    $rs['role'] = json_decode($query['roles']); // already a json format
    $json[] = $rs; 
}
exit(json_encode($json));// convert to json AJAX response works

那么json结果如下

{ 
    "academics":{ 
        "class":"true",
        "employee":"false",
        "students":"true",
        "subject":"false",
        "all":"true"
    },
    "exam":{ 
        "exams":"false",
        "schedule":"false",
        "result":"false",
        "marksheet":"false",
        "all":"false"
    },
    "timetable":{ 
        "class":"false",
        "teacher":"false",
        "all":"false"
    },
    "attendance":{ 
        "students":"true",
        "teacher":"true",
        "all":"true"
    }
}

未定义的 json 长度 [JAVASCRIPT]

// parse nested json 
var json = JSON.parse(data)

console.log(json.role) // works and print above json
console.log(json.role.length) // undefined

// for loop not works
for(i = 0; i < json.role.length; i++){

   for(y = 0; y < json.role[i].length; y++){
      // json.role.academics.class === true [if condition]
       if(json.role[i][y] === true){
         //......
       }
   }
}

【问题讨论】:

    标签: javascript php json


    【解决方案1】:

    上面的 JSON 是一个对象,这就是它的长度未定义的原因。

    您尝试读取数据的方式 - JSON 响应应该有一个通过“角色”属性引用的对象数组 - 以下格式应该可以工作。请检查回复。

    {
        "roles": [{
                "academics": {
                    "class": "true",
                    "employee": "false",
                    "students": "true",
                    "subject": "false",
                    "all": "true"
                }
            },
            {
                "exam": {
                    "exams": "false",
                    "schedule": "false",
                    "result": "false",
                    "marksheet": "false",
                    "all": "false"
                }
            },
            {
                "timetable": {
                    "class": "false",
                    "teacher": "false",
                    "all": "false"
                }
            },
            {
                "attendance": {
                    "students": "true",
                    "teacher": "true",
                    "all": "true"
                }
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2019-05-06
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多