从数据库获取数据并创建所需的JSON格式

时间:2014-11-08 17:04:45

标签: php json pdo

我有这个PHP代码从数据库activity获取数据:

try {

$dateString = '09.03.2014';
$startDate = new DateTime($dateString);
$endDate = clone $startDate;
$startDate = $startDate->format("U") . PHP_EOL;
$period = new DateInterval('P1M');

$endDate->add($period);
$endDate = $endDate->format("U") . PHP_EOL;

$interval = new DateInterval('P1D');
$sql = <<<EOD
SELECT timestamp_day,name FROM activity WHERE timestamp_day BETWEEN $startDate AND $endDate
ORDER BY timestamp_day
EOD;
$data = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$output = ['data' => $data];
$jsonTable = json_encode($output); //$date->format("U") . PHP_EOL;//format your date to timestamp here


    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;

此代码为我提供了日期和日期的数据,我得到了这个JSON:

data: [{timestamp_day:1394319600, name:Meeting}, {timestamp_day:1394319600, name:Car repair},…]
0: {timestamp_day:1394319600, name:Meeting}
1: {timestamp_day:1394319600, name:Car repair}
2: {timestamp_day:1394406000, name:Travel}
3: {timestamp_day:1394492400, name:Work}
4: {timestamp_day:1394578800, name:Vacation}

(从Chrome浏览器控制台复制)

现在你可以看到我有一些日期有两个记录(0-1),我想要放在同一个对象上,所以就像这样:

 {timestamp_day:1394319600, name:Meeting, Car repair}
 {timestamp_day:1394406000, name:Travel}
 {timestamp_day:1394492400, name:Work}
 {timestamp_day:1394578800, name:Vacation}

另外,我还有一个问题,我现在可以使用这个元素,因为我需要输入html代码:timestamp_day?

也没有记录的日期我需要放入JSON,以便类似:

 {timestamp_day:1394406000, name:'<a>No data</a>'}

一些想法?

1 个答案:

答案 0 :(得分:2)

使用GROUP_CONCAT组合记录中具有相同时间戳的值:

SELECT timestamp_day, GROUP_CONCAT(name SEPARATOR ', ') AS name 
FROM activity 
WHERE timestamp_day BETWEEN $startDate AND $endDate
GROUP BY timestamp_day
ORDER BY timestamp_day

P.S。你应该使用预备语句而不是变量替换。

以下是如何使用预准备语句并按天分组:

$stmt = $db->prepare("
    SELECT DATE(FROM_UNIXTIME(timestamp_day)) AS date, GROUP_CONCAT(name SEPARATOR ', ' ORDER BY timestamp_day) AS name 
    FROM activity 
    WHERE timestamp_day BETWEEN :startDate AND :endDate
    GROUP BY date
    ORDER BY date");
$stmt->bindParam(':startDate', $startDate);
$stmt->bindParam(':endDate', $endDate);
$stmt->execute();
$data = $stmt->fetchAll();