Reputation: 337
How can I merge the array with the same key(using date as a key) but different values? I used to create a code but the problem is the value that stores is only one per key but they have a same key(date).
Here's my array:
{
posting_date: "2017-08-08 00:00:00",
id: 1,
title: "activity 1",
category: "company_news"
},
{
posting_date: "2017-08-08 00:00:00",
id: 6,
title: "testing",
category: "building_process_update"
},
{
posting_date: "2017-08-08 00:00:00",
id: 7,
title: "ttest1",
category: "company_news"
},
Here's my code:
foreach ($result_post as $key => $value){
$year = date('Y',strtotime($value['posting_date']));
$month = date('M',strtotime($value['posting_date']));
$day = date('d',strtotime($value['posting_date']));
// $result[$year] = $value['posting_date'];
$data = [$value['title']];
$side_bar_date[$value['category']][$year][$month][$day] = ['id'=>$value['id'],'title'=>$value['title']];
}
but the output is
building_process_update: {
2017: {
Aug: {
08: {
id: 6,
title: "testing"
}
}
}
Upvotes: 0
Views: 62
Reputation: 2296
Please try below code
foreach ($result_post as $key => $value){
$year = date('Y',strtotime($value['posting_date']));
$month = date('M',strtotime($value['posting_date']));
$day = date('d',strtotime($value['posting_date']));
// $result[$year] = $value['posting_date'];
$data = [$value['title']];
$side_bar_date[$value['category']][$year][$month][$day][] = array('id'=>$value['id'],'title'=>$value['title']);
}
This is working in my case.
Upvotes: 1
Reputation: 12085
Your overwriting
the day
key consequently
. you need to push the value into day
key as array
[]
like below
$side_bar_date[$value['category']][$year][$month][$day][] = ['id'=>$value['id'],'title'=>$value['title']];
Upvotes: 2