I\'m thinking how to group my array by objects with the same value.
I have this result from MySQL query:
Date StartTime EndTim
EMPLOYER NAME DATA_PATH Alp 1. video_link 2. video_link Xyz 1. video_link 2. video_link 3. video_link
$stmt = $this->conn->prepare("SELECT a.employer_name,b.data_path FROM
rec_experience a INNER JOIN rec_multi_upload_data b
ON(a.rec_uniqueid=b.rec_id) WHERE b.data_type='Video' ORDER BY
a.c_date DESC ");
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$out = [];
foreach($res as $element)
{
$out[$element['employer_name']][] = ['video_link' =>
$element['data_path']];
}
echo json_encode($out);
Based on the structure outlined in the question:
Requires php 5.4+ for the json pretty printing, if you are on a lower version just remove it and use long array format.
$in = <<<'JSON'
[
{
"Date": "2014-12-01",
"StartTime": "10:00",
"EndTime": "16:00"
},
{
"Date": "2014-12-02",
"StartTime": "12:00",
"EndTime": "18:00"
},
{
"Date": "2014-12-03",
"StartTime": "10:00",
"EndTime": "20:00"
},
{
"Date": "2014-12-03",
"StartTime": "12:00",
"EndTime": "20:00"
}
]
JSON;
$data = json_decode($in, true);
$out = [];
foreach($data as $element) {
$out[$element['Date']][] = ['StartTime' => $element['StartTime'], 'EndTime' => $element['EndTime']];
}
var_dump(json_encode($out, JSON_PRETTY_PRINT));
To get the exact same output as in the question (the returned output wrapped in a single element json-array you'd need to wrap $out
in an other array like this:
json_encode([$out], JSON_PRETTY_PRINT)
Results in:
{
"2014-12-01": [
{
"StartTime": "10:00",
"EndTime": "16:00"
}
],
"2014-12-02": [
{
"StartTime": "12:00",
"EndTime": "18:00"
}
],
"2014-12-03": [
{
"StartTime": "10:00",
"EndTime": "20:00"
},
{
"StartTime": "12:00",
"EndTime": "20:00"
}
]
}