php 数组月份相加,PHP数组:将值与匹配日期相加

最初使用年/月/日的组合索引输出数组可能是最简单的:

注意:上面的示例数组的所有月份键都带有尾随空格.我只是在这里使用月份,没有尾随空格.

// Initialize output array...

$out = array();

// Looping over each input array item

foreach ($myArray as $elem) {

// Initialize a new element in the output keyed as yyyy-mm-dd if it doesn't already exist

if (!isset($out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']])) {

$out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']] = array(

// Set the date keys...

'year' => $elem['year'],

'month' => $elem['month '],

'day' => $elem['day'],

// With the current value...

'value' => $elem['value']

);

}

// If it already exists, just add the current value onto it...

else {

$out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']]['value'] += $elem['value'];

}

}

// Now your output array is keyed by date. Use array_values() to strip off those keys if it matters:

$out = array_values($out);

输出(在调用array_values()之前):

array(2) {

'2011-5-13' =>

array(4) {

'year' =>

int(2011)

'month' =>

int(5)

'day' =>

int(13)

'value' =>

int(3)

}

'2011-5-14' =>

array(4) {

'year' =>

int(2011)

'month' =>

int(5)

'day' =>

int(14)

'value' =>

int(14)

}

}

更新:

要用单键日期(而不是3个部分)做同样的事情,没有连接就更容易:

$myArray=array(

array(

'date' => '2011-05-13',

'value' => 2

),

array(

'date' => '2011-05-14',

'value' => 5

),

array(

'date' => '2011-05-13',

'value' => 7

),

array(

'date' => '2011-05-14',

'value' => 3

),

);

foreach ($myArray as $elem) {

// Initialize a new element in the output if it doesn't already exist

if (!isset($out[$elem['date']])) {

$out[$elem['date'] = array(

// Set the date keys...

'date' => $elem['date'],

// With the current value...

'value' => $elem['value']

);

}

else {

$out[$elem['date']]['value'] += $elem['value'];

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值