0

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] => 41
        )
)

So, how to get the 'distinct' of time_spent and also the 'sum' of the time_spent.

Thanks.

0

3 Answers 3

2

You can try:

$result = array_unique($input_array);
var_dump(array_sum($result['time_spent']));

Docs:

Sign up to request clarification or add additional context in comments.

2 Comments

@vishnu: Really you needs i doubt, Accept your previous question keep in mind.
i believe that call to array_unique wont be effective bc it doesnt work on multi-dimensional arrays. youd have to do it AFTER making parallel (using the term loosely) array of just time_spent values
2

Try this:

$sum = 0;
$timeSpent = array();
foreach($myArray as $element) {
    $timeSpent[] = $element['time_spent'];
    $sum += $element['time_spent'];
}

To have:

  1. $sum => The sum of all time_spent
  2. $time_spent => An array of all time spent (whitout URL)

1 Comment

hey, i need distinct sum of time_spent
1
$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)));

https://www.php.net/manual/en/ref.array.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.