在连续日期的子数组中拆分数组 [英] Split an array in sub arrays of consecutive dates
本文介绍了在连续日期的子数组中拆分数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于租金申请,我有一个数组$ date这样:
Array
pre>
(
[2013-07-19] => 1
[2013-07-21] => 3
[2013-07-23] => 2
[2013-07 -24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => ; 2
[2013-07-30] => 3
[2013-07-31] => 1
)
日期是关键字,值是特定产品当天租金的数量
如何将这个数组拆分成包含每个连续列表的多个子数组?
像这样:Array
(
[0] => ; Array
(
[2013-07-19] => 1
)
[1] =>数组
(
[2013-07-21] => 3
)
[2] => Array
(
[2013-07-23] => ; 2
[2013-07-24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => 2
)
[3] =>数组
(
[2013-07-30] => ; 3
[2013-07-31] => 1
)
)
解决方案你可以这样做:
$ data = array(
'2013-07-19'=> 1,
'2013-07-21'=> 3,
'2013-07-23'= > 2,
'2013-07-24'=> 4,
'2013-07-25'=> 4,
'2013-07-26'=> 2,
'20 13-07-27'=> 2,
'2013-07-30'=> 3,
'2013-07-31'=> 1
);
$ result = array();
$ ref = new DateTime('1821-11-11');
foreach($ data as $ datum => $ nb){
if($ ref-> add(new DateInterval('P1D')) - > format('Ym-d' != $ datum){
$ result [] = array();
$ ref = new DateTime($ datum);
}
$ result [array_pop(array_keys($ result))] [$ datum] = $ nb;
}
print_r($ result);
For a rent application, I have an array $dates like this:
Array ( [2013-07-19] => 1 [2013-07-21] => 3 [2013-07-23] => 2 [2013-07-24] => 4 [2013-07-25] => 4 [2013-07-26] => 2 [2013-07-27] => 2 [2013-07-30] => 3 [2013-07-31] => 1 )
The date is the key, and the values are the number of items rent in that day for a specific product
How can I split this array in many sub arrays containing each a list of consecutive days? Like this:
Array ( [0] => Array ( [2013-07-19] => 1 ) [1] => Array ( [2013-07-21] => 3 ) [2] => Array ( [2013-07-23] => 2 [2013-07-24] => 4 [2013-07-25] => 4 [2013-07-26] => 2 [2013-07-27] => 2 ) [3] => Array ( [2013-07-30] => 3 [2013-07-31] => 1 ) )
解决方案you can do it like this:
$data = array( '2013-07-19' => 1, '2013-07-21' => 3, '2013-07-23' => 2, '2013-07-24' => 4, '2013-07-25' => 4, '2013-07-26' => 2, '2013-07-27' => 2, '2013-07-30' => 3, '2013-07-31' => 1 ); $result = array(); $ref = new DateTime('1821-11-11'); foreach ($data as $datum => $nb) { if ($ref->add(new DateInterval('P1D'))->format('Y-m-d')!=$datum) { $result[] = array(); $ref = new DateTime($datum); } $result[array_pop(array_keys($result))][$datum] = $nb; } print_r($result);
这篇关于在连续日期的子数组中拆分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文