JSON MySQL为开始和结束之间的每个日期添加到JSON编码

时间:2012-09-18 15:48:29

标签: php arrays associative-array json

我在MySQL中有一个表startdateenddate

一行的例子是(忽略整个命名):

eg 
startdate -> 20121224
endate -> 20121226
title -> name
etc

我目前的脚本效果很好,并为每一行添加了JSON,但是...... 我想....为每个mysql行获取startdate和enddate,对于startdate和enddate中包含的每个日期添加到JSON编码。

因此,而不是上面的1行返回示例:

[{
    "user": "378",
    "date": "UNIX_TIMESTAMP(startdate)",
    "title": "name",
    "description": "6 Days",
    "url": "UNIX_TIMESTAMP(enddate)",
    "bmanager": "manager name",
    "academic_year": "20120801",
    "division": "division name",
    "manager_id": "3"
}]

每个日期的一行会返回3个JSON:

[{
    "user": "378",
    "date": "UNIX_TIMESTAMP(1st date)",
    "title": "name",
    "description": "6 Days",
    "url": "UNIX_TIMESTAMP(1st date)",
    "bmanager": "manager name",
    "academic_year": "20120801",
    "division": "division name",
    "manager_id": "3"
}, {
    "user": "378",
    "date": "UNIX_TIMESTAMP(2nd date)",
    "title": "name",
    "description": "6 Days",
    "url": "UNIX_TIMESTAMP(2nd date)",
    "bmanager": "manager name",
    "academic_year": "20120801",
    "division": "division name",
    "manager_id": "3"
}, {
    "user": "378",
    "date": "UNIX_TIMESTAMP(3rd date)",
    "title": "name",
    "description": "6 Days",
    "url": "UNIX_TIMESTAMP(3rd date)",
    "bmanager": "manager name",
    "academic_year": "20120801",
    "division": "division name",
    "manager_id": "3"
}, ]

JSON

<?php
    header('Content-type: text/json');

    $lmanager = $_GET["lmanager"];

    $sqldata = mysql_query('
    SELECT
    requests.user,
    UNIX_TIMESTAMP(requests.start_date) AS date,
    requests.employee AS title, 
    requests.days AS description,
    UNIX_TIMESTAMP(requests.end_date) AS url,
    business.line_manager AS bmanager,
    requests.academic_year,
    business.academic_year,
    business.division,
    line_managers.userid AS manager_id
    FROM requests 
    INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
    INNER JOIN line_managers ON business.line_manager=line_managers.name
    WHERE requests.approved = 1 AND line_managers.userid = '.$lmanager.'
    ');

    $posts = array();

    while($row = mysql_fetch_assoc($sqldata))
    {
        $row['date'] = $row['date'].'000';
        $row['url'] = $row['url'].'000';
        $row['description'] = $row['description'].' Days';
        $posts[] = $row;
    }

    mysql_free_result($sqldata);
    die(json_encode($posts));
?>

1 个答案:

答案 0 :(得分:1)

将此添加到您的sql select查询中:

select datediff(requests.end_date, requests.start_date) as numdays

然后做这样的事情:

while($row = mysql_fetch_assoc($sqldata))
{
    for($i = 0; $i < $row['numdays']; $i++){
        $row['date'] = $row['date']+$i*24*60*60; // add 24 hours in seconds to the start_date stamp
        $posts[] = $row;
    }
}

您可能需要调整它,