0

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"
                    }
                 }
             }
2
  • post the expected result Commented Aug 10, 2017 at 9:12
  • I've already edit the exact output Commented Aug 10, 2017 at 9:16

2 Answers 2

2

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']];
Sign up to request clarification or add additional context in comments.

1 Comment

Glad it help you @clien
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.