欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于操作php 数组,进行相关计算的问题

程序员文章站 2024-02-06 12:09:52
...
$arr = array(
    array(
        'imp' => 1000,
        'clk' => 100,
        'date' => 20150601
    ),
    array(
        'imp' => 1002,
        'clk' => 102,
        'date' => 20150602
    ),
    array(
        'imp' => 1003,
        'clk' => 103,
        'date' => 20150601
    )

);

求这个数组里相同日期的曝光总和、点击总和,用最简洁的代码表示出来
imp 曝光
clk 点击
date 日期

回复内容:

$arr = array(
    array(
        'imp' => 1000,
        'clk' => 100,
        'date' => 20150601
    ),
    array(
        'imp' => 1002,
        'clk' => 102,
        'date' => 20150602
    ),
    array(
        'imp' => 1003,
        'clk' => 103,
        'date' => 20150601
    )

);

求这个数组里相同日期的曝光总和、点击总和,用最简洁的代码表示出来
imp 曝光
clk 点击
date 日期

php$a=array();
foreach($arr as $v){
    $a[$v['date']]['clk']+=$v['clk'];
    $a[$v['date']]['imp']+=$v['imp'];
}
print_r($a);

php$res=[];
foreach ($arr as $key => $value) {
  $res[$value['date']] =array(
      'imp' =>isset($res[$value['date']]) ? $res[$value['date']]['imp']+$value['imp'] : $value['imp'],
      'clk' =>isset($res[$value['date']]) ? $res[$value['date']]['clk']+$value['clk'] : $value['clk'],
      'date' =>$value['date']
  );
}
print_r(array_values($res));
Array
(
    [0] => Array
        (
            [imp] => 2003
            [clk] => 203
            [date] => 20150601
        )

    [1] => Array
        (
            [imp] => 1002
            [clk] => 102
            [date] => 20150602
        )

)

$tmp = array();
foreach($arr as $k => $v) {
    $tmp[$k] = $v['date'];
}
$tmp = array_unique($tmp);
/* 去重后得
Array
(
    [0] => 20150601
    [1] => 20150602
)
*/

$tmp2 = array();
foreach($tmp as $k => $v) {
    $tmp2[$v]['imp'] = 0;
    $tmp2[$v]['clk'] = 0;
}
/* 初始化得
Array
(
    [20150601] => Array
        (
            [imp] => 0
            [clk] => 0
        )

    [20150602] => Array
        (
            [imp] => 0
            [clk] => 0
        )

)
*/

foreach($tmp as $k => $v) {
    foreach($arr as $k2 => $v2) {
        if($v == $v2['date']) {
            $tmp2[$v]['imp'] += $v2['imp'];
            $tmp2[$v]['clk'] += $v2['clk'];
        }
    }
}
print_r($tmp2);
/* 求和得
Array
(
    [20150601] => Array
        (
            [imp] => 2003
            [clk] => 203
        )

    [20150602] => Array
        (
            [imp] => 1002
            [clk] => 102
        )

)
*/

来个reduce版本

 1000,
        'clk' => 100,
        'date' => 20150601
    ),
    array(
        'imp' => 1002,
        'clk' => 102,
        'date' => 20150602
    ),
    array(
        'imp' => 1003,
        'clk' => 103,
        'date' => 20150601
    )

);


$result = array_reduce($arr, function($left, $right) {
    if(isset($right['imp'])) $left['imp'] += $right['imp'];
    if(isset($right['clk'])) $left['clk'] += $right['clk'];

    return $left;
}, [
    'imp' => 0,
    'clk' => 0
]);

print_r($result);

http://3v4l.org/58v94

专业问题。。学习了

相关标签: php