php - Get data from database and create needed JSON format -
php - Get data from database and create needed JSON format -
i have php code fetch info database 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 activity timestamp_day between $startdate , $enddate order timestamp_day eod; $data = $db->query($sql)->fetchall(pdo::fetch_assoc); $output = ['data' => $data]; $jsontable = json_encode($output); //$date->format("u") . php_eol;//format date timestamp here } catch(pdoexception $e) { echo 'error: ' . $e->getmessage(); } echo $jsontable;
this code give me info date date , 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}
(copied chrome browser console)
now can see have dates 2 records (0-1) , want set on same object this:
{timestamp_day:1394319600, name:meeting, auto repair} {timestamp_day:1394406000, name:travel} {timestamp_day:1394492400, name:work} {timestamp_day:1394578800, name:vacation}
also have 1 more question how can work element becouse need set in html code: timestamp_day ?
also dates dont have record nee set in json like:
{timestamp_day:1394406000, name:'<a>no data</a>'}
some ideas?
use group_concat
combine values records same timestamp:
select timestamp_day, group_concat(name separator ', ') name activity timestamp_day between $startdate , $enddate grouping timestamp_day order timestamp_day
p.s. should utilize prepared statements instead of variable substitution.
here's how utilize prepared statement , grouping day:
$stmt = $db->prepare(" select date(from_unixtime(timestamp_day)) date, group_concat(name separator ', ' order timestamp_day) name activity timestamp_day between :startdate , :enddate grouping date order date"); $stmt->bindparam(':startdate', $startdate); $stmt->bindparam(':enddate', $enddate); $stmt->execute(); $data = $stmt->fetchall();
php json pdo
Comments
Post a Comment