Dear Friends,

I have a string with structure

$selectedTime = "2017-02-10 07:00,2017-02-10 08:00,2017-02-11 09:00";

I need to convert it as

{"2017-02-10":[{"start":"07:00"},{"start":"08:00"}],"2017-02-11":[{"start":"09:00"}]}

any idea ? please advise asap

Thanks
Anes

Dani AI

Generated

Credit to for the practical solution: the core idea — parse each timestamp, sort chronologically, then group slots by date — is exactly the right pattern for this problem. That approach is compact and works well for small, well-formed inputs.

A few practical gotchas to keep in mind. Using numeric timestamps as array keys can silently drop duplicate entries with the same second; avoid that by sorting a list of parsed DateTime objects instead of using the timestamp as a unique key. Validate and trim tokens before parsing, and prefer DateTime parsing (PHP) or datetime.strptime (Python) over blind string manipulation so unexpected formats and time zones are handled more predictably. Finally, JSON object key order is not guaranteed by the spec — if a consumer requires stable ordering, emit an array of {date, slots} objects rather than relying on object key order.

A robust PHP pattern (parsing, sorting, grouping):

<?php
$input = /* comma-separated datetimes */;
$tokens = array_filter(array_map('trim', explode(',', $input)));

$rows = [];
foreach ($tokens as $t) {
    $dt = DateTime::createFromFormat('Y-m-d H:i', $t);
    if ($dt) $rows[] = $dt;
}

usort($rows, function($a, $b){
    return $a->getTimestamp() <=> $b->getTimestamp();
});

$result = [];
foreach ($rows as $dt) {
    $date = $dt->format('Y-m-d');
    $result[$date][] = ['start' => $dt->format('H:i')];
}

echo json_encode($result);

A concise Python alternative:

import json
from datetime import datetime
from collections import defaultdict

s = '...'  # input string
parts = [p.strip() for p in s.split(',') if p.strip()]
parsed = []
for p in parts:
    try:
        parsed.append(datetime.strptime(p, '%Y-%m-%d %H:%M'))
    except ValueError:
        continue

parsed.sort()
out = defaultdict(list)
for dt in parsed:
    out[dt.date().isoformat()].append({'start': dt.strftime('%H:%M')})

print(json.dumps(out))

Troubleshooting tips: normalize separators, skip invalid tokens, decide how to handle duplicates, and choose an output shape (object vs array) according to whether ordering must be preserved.

Dear Friends,

With the Help of my Friend Vishnu A.R I solved the issue

my required Code is

<?php
$selectedTime = "2017-02-10 08:00,2017-02-10 07:00,2017-02-11 09:00";

$arr1 = explode(",", $selectedTime);

$arr2 = array();

foreach($arr1 as $time){
  $strtime = strtotime($time);
  $arr2[$strtime] = $time;
}
ksort($arr2); // sorting array in ascending order of key value
$arr3 = array();
foreach($arr2 as $key => $time){
  $timesplit = explode(" ", $time);

  $arr3[$timesplit[0]][] = array('start' => $timesplit[1]);
}
$output = json_encode($arr3);
var_dump($output);
?>

Thanks

Anes

commented: Here I thought a regular expression may do. This works too. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.