PHP自定义json_encode使用MySQL加入格式化

时间:2015-08-10 02:01:53

标签: php ajax json

我正在创建一个项目时间跟踪工具。我是JOINS的菜鸟。我对非关系型数据库的经验更丰富。

我有一个带有两个表的MySQL数据库。一个用于名为" Projects"的列表或项目,另一个用于保存每个会话,名为" ProjectLogs"。每个会话都有一个开始和停止时间戳。

"项目"表看起来像这样:

p_id, projectname

" ProjectLogs"看起来像这样:

id, project_id, starttime, endtime

我使用PHP来LEFT JOIN,使用:

$sql = "SELECT *
FROM Projects
LEFT JOIN ProjectLogs
ON Projects.p_id=ProjectLogs.project_id";

然后我得到了结果:

$result = mysqli_query($con, $sql);

然后我需要将$ result转换为JSON,所以我使用它:

$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
    $emparray[] = $row;
} 
header('Content-Type: application/json');
echo json_encode($emparray);

我回来的是这个。每个TimeLog的不同对象:

[
    {
        "p_id":"1",
        "projectname":"Project 001",
        "id":"1",
        "project_id":"1",
        "starttime":"2015-08-09 19:37:02",
        "endtime":"2015-08-09 19:39:13"
    }
]

我想要的是这样的东西,其中Logs是项目内部的一个数组:

[
    {
        "p_id": "1",
        "projectname": "Project 001"
        "ProjectLogs": [
            {
                "id": "1", 
                "project_id": "1",
                "starttime": "2015-08-09 19:44:24", 
                "endtime": "2015-08-09 20:00:17"
            },
            {
                "id": "2", 
                "project_id": "1",
                "starttime": "2015-08-09 19:44:24", 
                "endtime": "2015-08-09 20:00:17"
            }
        ]
    },
    {
        "p_id": "2",
        "projectname": "Project 002"
        "ProjectLogs": [
            {
                "id": "1", 
                "project_id": "2",
                "starttime": "2015-08-09 19:44:24", 
                "endtime": "2015-08-09 20:00:17"
            },
            {
                "id": "2", 
                "project_id": "2",
                "starttime": "2015-08-09 19:44:24", 
                "endtime": "2015-08-09 20:00:17"
            }
        ]
    }
]

非常感谢任何帮助!我觉得这是一个重复的问题,但我并不确定要搜索什么。

1 个答案:

答案 0 :(得分:0)

我想出了答案。如果有人有兴趣,这是解决方案:

$sql = "SELECT *
FROM Projects
LEFT JOIN ProjectLogs
ON Projects.p_id=ProjectLogs.project_id
ORDER BY Projects.p_id";

$result = mysqli_query($con, $sql);

// create an empty array that you can send 
// to json_encode later
$arr = array();

// Loop through the results
while($row = mysqli_fetch_assoc($result)) {
    // Check to see if the result contains a 'project_id' key
    // If it doesn't, then this isn't a result with a ProjectLog
    if( $row['project_id'] != "" ) {
        // Set the key vaue pairs for the Project
        $arr[$row['p_id']]['p_id'] = $row['p_id'];
        $arr[$row['p_id']]['projectname'] = $row['projectname'];
        // Now we need to check to see if any timelogs have been
        // pushed to $arr.
    if(array_key_exists("timelogs", $arr[$row['p_id']]) )   {
        // Since it does exist:
        // Create a variable to store the 3 values we need,
        // And push them to the existing timelogs array
        $val = array(
            'id' => $row['id'],
        'starttime' => $row['starttime'],
        'endtime' => $row['endtime']
        );
        array_push($arr[$row['p_id']]['timelogs'], $val);
    } else {
            // Since it doesn't exist, lets create the timelogs array
        $arr[$row['p_id']]['timelogs'] = array(
            array(
                'id' => $row['id'],
                'starttime' => $row['starttime'],
                'endtime' => $row['endtime']
            )
        );  
    } 
  }else {
    // This fires when there are no ProjectLogs yet, just an empty project
    $arr[$row['p_id']]['p_id'] = $row['p_id'];
    $arr[$row['p_id']]['projectname'] = $row['projectname'];
  }
}

// Apparently this is required
header('Content-Type: application/json');
// Go time! JSON!
echo json_encode($arr);