一开始:我特别喜欢PHP和数组,但我尽力学习。我很感谢能得到的每一个帮助。
现在我绝望地尝试从多维数组计算总和,如下所示:
Date -> Medium -> Device -> KPI
在一个例子中:
2014-09-10 :: organic :: desktop :: visits == 10<br>
2014-09-10 :: organic :: tablet :: visits == 3<br>
2014-09-10 :: organic :: desktop :: conversion = 1.9<br>
2014-09-10 :: organic :: tablet :: conversion = 1.2<br>
2014-09-10 :: paid :: desktop :: visits == 9<br>
2014-09-10 :: paid :: tablet :: visits == 4<br>
2014-09-10 :: paid :: desktop :: conversion = 3.4<br>
2014-09-10 :: paid :: tablet :: conversion = 3.1
问题1:如何计算所有访问次数或所有转化率的总和?
问题2:如何计算例如平板电脑的所有转换率?
我尝试使用array_sum,但无法弄清楚如何在不同的参数上分解它。我在考虑像array_sum($thearray['2014-09-10']['visits']
这样的东西,但这可能是为了容易思考。
您对如何找到解决方案有任何想法吗?
非常感谢!
答案 0 :(得分:1)
我会用伪PHP代码编写它,这不是我的语言,但想法是通用的。
function sum($obj, $label){
if( !is_array($obj) ){
return 0;
}
$count = 0;
foreach($obj as $key=>$val){
if($key === $label){
$count += $val;
}
if( is_array($val) ){
$count += sum($val, $label);
}
}
return $count;
}
答案 1 :(得分:0)
$visits = 0;
foreach($arr as $item)
$visits += $item ['visits'];
echo $visits;
答案 2 :(得分:0)
$items = array(
array( 'date' => '2014-09-10','type' => 'desktop', 'visits' => 10 ),
array( 'date' => '2014-09-10', 'type' => 'tablet', 'conversion' => 5 ),
array( 'date' => '2014-09-10', 'type' => 'desktop', 'visits' => 10 ),
array( 'date' => '2014-09-10', 'type' => 'desktop', 'visits' => 10 ),
array( 'date' => '2014-09-10','type' => 'tablet', 'conversion' => 10 ),
array( 'date' => '2014-09-10', 'type' => 'desktop', 'visits' => 5 )
);
// sum of `visits`
$sum = array_sum(array_map(function($item){
return $item['visits'];
},$items));
var_dump($sum);
// sum of `visits` by type `tablet`
$sum = array_sum(array_map(function($item){
return ($item['type']=='tablet')?$item['visits']:null;
},$items));
var_dump($sum);