数组合并取决于数组键

时间:2017-08-10 09:11:22

标签: php arrays

如何将数组与相同的键合并(使用日期作为键)但值不同?我曾经创建过一个代码,但问题是每个密钥存储的值只有一个,但它们有相同的密钥(日期)。

这是我的阵列:

          {
                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"
          },

这是我的代码:

    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']];

    }

但输出是

   building_process_update: {
             2017: {
                 Aug: {
                    08: {
                       id: 6,
                       title: "testing"
                    }
                 }
             }

2 个答案:

答案 0 :(得分:2)

您的overwriting day密钥consequently。您需要将值day改为array [],如下所示

$side_bar_date[$value['category']][$year][$month][$day][] = ['id'=>$value['id'],'title'=>$value['title']];

答案 1 :(得分:1)

请尝试以下代码

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']);
    }

这适用于我的情况。