PHP数组分裂成小数组


PHP array split into small 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中做到这一点?

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

$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);
演示

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

然后使用循环遍历。这将产生一个多维数组$datesArr,其中包含$datesArr[年][月]。这样,您可以简单地拆分整个数组或使用完整索引的数组。

 $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。如果你有问题,请回答我!

祝你好运!