2

I have these arrays:

Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([265] => 9.00)
Array ([326] => 20.00)

I want to count the amount of reptitions and their corresponding sum:

265 repeated 4 times and the sum of it's value is 36

326 repeated 1 time and the sum of it's value is 20

I would appreciate your help.

Thanks

1
  • 8
    If I give you the hints array_merge_recursive & array_sum, what code can you come up with? Commented Dec 7, 2013 at 9:30

3 Answers 3

1
$total = array();
foreach($arrays as $array) {
    foreach($array as $key => $value) {
        if (!isset($total[$key])) {
            $total[$key]['hits'] = 0;
            $total[$key]['count'] = 0;
        }

        $total[$key]['hits']++;
        $total[$key]['count']+= $value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Check out my code, Function: http://phpfiddle.org/main/code/7ia-40m

$a = array ( array( 265 => '9.00'), array(265 => '9.00'), array(326 => '20.00') );

echo '<pre>'; print_r(getDetails($a)); echo '</pre>';

function getDetails($array) {
    $a = $array;
    $b = array();
    foreach($a as $ar) {
        $n=0;
        foreach($ar as $k => $v) {
            $n++;
            if(isset($b[$k])) {
                $b[$k]['val'] = ($b[$k]['val'] + $v);
                $b[$k]['total']++;
            } else {
                $b[$k]['val'] = (0 + $v);
                $b[$k]['total'] = (1);
            }

        }

    }

    $string = '';
    foreach($b as $k => $arr) {
        $val = $arr['val']; $key = $k; $tot = $arr['total'];
        $string .= $key.' repeated '.$tot.' times. Sum : '.$val.' <br />';
    }

    return $string;

}

Result:

265 repeated 2 times. Sum : 18 
326 repeated 1 times. Sum : 20

Comments

0

Check This

    <?php
$arr=array(
      array('265'=>'5'),
      array('265'=>'5'),
      array('265'=>'1'),
      array('280'=>'3')
);


$sets = array();
foreach($arr as $array)
{   
   foreach($array as $arrayset=>$cent)
  {

    $sets[$arrayset][] = $cent;

    if(isset($abc[$arrayset])) // prevent index warning
    {           
        $abc[$arrayset] += $cent;
    }
    else
    {
        $abc[$arrayset] = $cent;
    }
  }
}
echo "<pre>";
print_r($abc);

?>

Output

Array
(
    [265] => 11
    [280] => 3
)

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.