PHP数组拆分成小数组

时间:2015-09-10 21:34:28

标签: php arrays

我有不同月份和年份的数组。我想按月和年分开

$array = array(
    '2013-01-01' => 3432,
    '2013-01-04' => 321,
    '2013-01-12' => 343,
    '2013-01-03' => 321,
    '2013-01-15' => 421,
    '2013-02-03' => 123,
    '2013-02-11' => 343,
    '2013-02-13' => 332,
    '2013-03-03' => 123,
    '2013-04-11' => 343,
    '2013-04-13' => 332,
    '2013-04-11' => 343,
    '2013-04-13' => 332,
    '2014-02-13' => 332,
    '2014-02-03' => 123,
    '2014-02-11' => 343,
    '2015-05-13' => 332,
    '2015-05-11' => 343,
    '2015-05-10' => 132,
    '2015-05-13' => 312
);

我想分成像

这样的小数组
$array1 = array(
    '2013-01-01' => 3432,
    '2013-01-04' => 321,
    '2013-01-12' => 343,
    '2013-01-03' => 321,
    '2013-01-15' => 421,
);

$array2 = array(
    '2013-02-03' => 123,
    '2013-02-11' => 343,
    '2013-02-13' => 332,
);

$array3 = array(
    '2013-03-03' => 123,
);

$array4 = array(
    '2013-04-11' => 343,
    '2013-04-13' => 332,
    '2013-04-11' => 343,
    '2013-04-13' => 332,
);

我每个月和每年都有偶像。

如何使用PHP执行此操作?

2 个答案:

答案 0 :(得分:1)

使用二维数组。第一个维度是年 - 月,这些值是子数组。

$new_array = array();
foreach ($array as $date => $value) {
    $parts = explode('-', $date);
    $year_month = $parts[0].'-'.$parts[1];
    if (!isset($new_array[$year_month])) {
        $new_array[$year_month] = array();
    }
    $new_array[$year_month][$date] = $value;
}
var_dump($new_array);

DEMO

答案 1 :(得分:0)

我在那里进行排序毫无意义,因为数组正在下面排序。

然后通过循环使用itterate。这将生成一个多维数组$ datesArr,它将包含$ datesArr [years] [months]。有了这个,您可以简单地拆分整个数组或使用完整的索引数组。

 $datesArr = array();
 $curYear = null;
 $curMonth = null;
 foreach ($array as $arrKey => $arrVal){
     $thisYr = date('Y', strToTime($arrKey));
     $thisMo = date('m', strToTime($arrKey));
     if (!isset($datesArr[$thisYr])){
         $curYear = $thisYr;
         $datesArr[$thisYr] = array();
     }
     if (!isset($datesArr[$thisYr][$thisMo])){
         $curMonth = $thisMo;
         $datesArr[$thisYr][$thisMo] = array();
     }
     $datesArr[$curYear][$curMonth][$arrKey] = $arrVal;
 }
print_r($datesArr);

我已经测试了这段代码,它完全像我说的那样lol。如果您有任何问题请回复我们!

祝你好运!