2010-03-11 122 views
-1

如何將此perl子例程轉換爲PHP函數?perl to 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) { 
    } 
} 

回答

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 ...; 
    } 
} 
+0

在這個表達式中「&」的用途是什麼:「... *&$ distance_metric($ cat_a,$ cat_b)}」? – Alex 2010-03-16 15:11:06

1
foreach my $cat_a (keys %aggregate) 

成爲

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

假設$骨料是一個關聯數組。

+0

AFAIK,PHP中的所有數組都是關聯的。 – Tomalak 2010-03-11 16:40:26