来自PhP编码的复杂嵌套JSON数组

时间:2015-09-14 18:43:43

标签: php mysql arrays json

我已经从数据库中创建了一个JSON文件,该文件有两个表semone,其中包含属性id,semester,cname和table courses,其中包含属性coname和credit。

我在php中编写的代码正在关注。

main.php

<?php
    $user = "root";
    $password = "";
    $database = "scheduler";

    $con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect"); 


    $query = "SELECT semone.userid AS sbuid, semone.semester AS semester, 
                      semone.cname AS name, courses.credit AS value, 
                      courses.progskill AS skill
              FROM semone
              INNER JOIN courses ON semone.cname = courses.coname" ;

    $result = mysqli_query($con,$query)or die ("Unable to connect");

    $info = array();
    $test = array();

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {

        $row['xyz'] = array(
                            'name'=> $row['name'],
                            'value'=> $row['value']    
                           );

        $info[$row['semester']]['children'][]= $row['xyz'];

        $data = json_encode(array('id' => $row['sbuid'], 'children' => $info));
    }
    echo $data;
?>

我想获取JSON文件,如下面的代码所示,但我得到的是这样的东西。

output.json

  {"id":"12345", 
        "children":

        {"first":
        {"children":
        [{"name":"CSE101","value":"100"},
       {"name":"CSE102","value":"100"}]},

        "second":
        {"children":
      [{"name":"CSE103","value":"50"}, 
      {"name":"CSE104","value":"100"},
      {"name":"CSE105","value":"100"}]},

        "third":
        {"children":
        [{"name":"CSE106","value":"50"}]}
         }}

但这正是我所期待的。

expected.json

{
 "id": 12345,
 "children":
  [{
     "semester": "first",
     "children": 
     [{
     "name": "C101","value": 100},
      { "name": "C102","value": 100}]
    }, 
    {
    "semester": "second",
      "children": 
      [{
     "name": "C103", "value": 50}, 
     {"name": "C104","value": 100}, 
     {"name": "C105","value": 100}]
}, 
{
 "semester": "third",
 "children":  
  [{"name": "C106","value": 50}]
 }
}

1 个答案:

答案 0 :(得分:2)

用以下内容替换你的while循环:

$lastId = null;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {

    $row['xyz'] = array(
                        'name'=> $row['name'],
                        'value'=> $row['value']    
                       );

    $info[$row['semester']]['semester'] = $row['semester'];
    $info[$row['semester']]['children'][]= $row['xyz'];

    $lastId = $row['sbuid'];
}

// do not call json_encode on each iteration of the loop
$data = json_encode(array('id' => $lastId, 'children' => array_values($info)));

<强> EXPLENATION

您希望$row['semester']成为children对象的字段,但您将此值设置为关键字。您需要使用semester键显式设置此值(与深children数组平行)并使用array_values在编码之前删除键(关联数组编码为对象,而数字编码为数组) )。

此外,我还没有想到只保存JSON中的最后一个$row['sbuid'],也许你想在这里做些不同的事情?

详细了解PHP的arraysjson encode