tags:

views:

108

answers:

2

How do you translate this perl subroutine into a PHP function?

sub disagreement {
  my $disagreement = 0;
  my %aggregate = () ;
  foreach my $item (@_) {$aggregate{$item}++}
  foreach my $cat_a (keys %aggregate) {
    foreach my $cat_b (keys %aggregate) {
      if ($cat_a != $cat_b) {$disagreement += $aggregate{$cat_a} * $aggregate{$cat_b} * &$distance_metric ($cat_a , $cat_b)}
    }
  }
  $disagreement /= @_ * (@_ - 1) ;
  return ($disagreement) ;
}

I have a problem here:

foreach my $cat_a (keys %aggregate) {
    foreach my $cat_b (keys %aggregate) {
    }
}
+1  A: 
foreach my $cat_a (keys %aggregate)

becomes

foreach ($aggregate as $key => $cat_a)

assuming $aggregate is an associative array.

Mike Thomsen
AFAIK, all arrays in PHP are associative.
Tomalak
+3  A: 
// &$... is a value reference instead of a value copy, when in doubt use $...
foreach ($aggregate as $cat_a => &$val_a) {
  foreach ($aggregate as $cat_b => &$val_b) {
    if ($cat_a !== $cat_b) $disagreement += $val_a * $val_b ...;
  }
}
Tomalak
Alex