如何将这个perl子例程转换为PHP函数?
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) ;
}
我有一个问题:
foreach my $cat_a (keys %aggregate) {
foreach my $cat_b (keys %aggregate) {
}
}
答案 0 :(得分:3)
// &$... 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 ...;
}
}
答案 1 :(得分:1)
foreach my $cat_a (keys %aggregate)
变为
foreach ($aggregate as $key => $cat_a)
假设$ aggregate是一个关联数组。