如何在php中创建一个由多个数组对象编码的json?

时间:2014-01-08 11:55:29

标签: php json

我有两个表名,分别是频道和部门。

$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result)){
    $fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'"); 
    $json2 = array();
    while ($row = mysql_fetch_array($fetch)){
        $json2[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]    
        );
    }
    $json['department'] = $json2;
    echo json_encode($json);
}

输出:

{
  "id": "1",
  "channelname": "con",
  "channelurl": "http:\/\/xxx.net\/YY\/",
  "department": [
    {
      "departmentname": "xxx Travel",
      "departmentid": "1"
    },
    {
      "departmentname": "xxxx Virtual Assist",
      "departmentid": "2"
    },
    "departmentname": "xxx  Premier",
    "departmentid": "3"
  },
  {
    "departmentname": "xxxx Events",
    "departmentid": "4"
  }
]
}{
"id": "2",
"channelname": "Slim",
"channelurl": "http:\/\/xxxxx.net\/slim\/",
"department": [
  {
    "departmentname": "Virtualvideo",
    "departmentid": "5"
  }
]
}

预期成果:

2 个答案:

答案 0 :(得分:1)

试试这个:

$json_channel = array();
$json_final = array();
$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result))
{
    $fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'");     
    $json_dept = array();

    while ($row = mysql_fetch_array($fetch))
    {
        $json_dept[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]);
    }

    $json_channel = array('id' => $json["ch_id"], 'channelname' =>$json["channelname"], 'department' => $json_dept);    

    $json_final[] = $json_channel;
}
echo json_encode($json_final);

答案 1 :(得分:0)

$output = array();
$result = mysql_query("SELECT * FROM channels");
while($json = mysql_fetch_assoc($result)){

    $fetch = mysql_query("SELECT * FROM departments where channelid='".$json['id']."'"); 
    $json2 = array();
    while ($row = mysql_fetch_array($fetch)){
        $json2[] = array('departmentname' => $row["departmentname"],'departmentid' => $row["did"]    
        );
    }

    $json['department'] = $json2;
    $output[] = $json;   
}
echo json_encode($output);