Get distinct sum from an php array
I have an array like this:
Array
(
[0] => Array
(
[url_id] => 1
[time_spent] => 41
)
[1] => Array
(
[url_id] => 2
[time_spent] => 25
)
[2] => Array
(
[url_id] => 1
[time_spent] =>开发者_StackOverflow中文版 41
)
)
So, how to get the 'distinct' of time_spent and also the 'sum' of the time_spent.
Thanks.
You can try:
$result = array_unique($input_array);
var_dump(array_sum($result['time_spent']));
Docs:
- array_unique
- array_sum
Try this:
$sum = 0;
$timeSpent = array();
foreach($myArray as $element) {
$timeSpent[] = $element['time_spent'];
$sum += $element['time_spent'];
}
To have:
- $sum => The sum of all time_spent
- $time_spent => An array of all time spent (whitout URL)
$ts = array_map(function ($a) {return $a['time_spent'];}, $arr); //get array of time_spent's
$sum = array_sum($ts); //sum
$distinct = array_unique($ts); //distincts
One-liner for sum of distinct values
$ans = array_sum(array_unique(array_map(function ($a) {return $a['time_spent'];}, $arr)));
http://us3.php.net/manual/en/ref.array.php
精彩评论