2014-06-19 144 views
0

的項目我與這些得分值的數組:PHP分配分數陣列

$r = Array 
(
    [C] => 11.00.00 
    [B] => 11.00.00 
    [G] => 11.00.00 
    [F] => 10.02.00 
    [A] => 10.00.00 
    [D] => 09.00.00 
    [E] => 08.00.00 
    [H] => 08.00.00 
    [I] => 07.00.00 
    [K] => 06.00.00 
    [J] => 06.00.00 
) 

我需要指定一個數字的位置,但是,同樣的分數將具有相同的位置,例如:

A : 1 -- draw score 
B : 1 -- draw score 
C : 1 -- draw score 
D : 4 -- not 2, because the previous position 
E : 5 -- normal 
F : 6 -- normal 
G : 7 -- draw score 
H : 7 -- draw score 
I : 9 -- not 8, because the previous position 
... 

我已經試過分數組項目,並與編號開始:

$result = array(); 
foreach($r as $k => $v) 
{ 
    $result[$k] = array_keys($r, $r[$k]); 
} 

編號

$p = $c = 1; 
foreach($result as $k => $v) 
{ 

    $ac = count($v); 
    if($ac==1) 
    { 
     $p = $p+$c; 
     $c = 1; 
    } 
    else 
    { 
     $c = $ac; 
    } 
    $result[$k] = $p; 
} 

print_r($result); 

,但我有這樣的:

Array 
(
    [C] => 1 
    [B] => 1 
    [G] => 1 
    [F] => 4 
    [A] => 5 
    [D] => 6 
    [E] => 6 
    [H] => 6 
    [I] => 8 
    [K] => 8 
    [J] => 8 
) 

我需要:

Array 
(
    [C] => 1 
    [B] => 1 
    [G] => 1 
    [F] => 4 
    [A] => 5 
    [D] => 6 
    [E] => 7 
    [H] => 7 
    [I] => 9 
    [K] => 10 
    [J] => 10 
) 

我怎樣才能正確排序?

回答

2
$result = Array 
(
    "C" => "11.00.00", 
    "B" => "11.00.00", 
    "G" => "11.00.00", 
    "F" => "10.02.00", 
    "A" => "10.00.00", 
    "D" => "09.00.00", 
    "E" => "08.00.00", 
    "H" => "08.00.00", 
    "I" => "07.00.00", 
    "K" => "06.00.00", 
    "J" => "06.00.00" 
); 

$prev=''; 
$i=1; 
foreach ($result as $key => $value) { 
$ii = $i++; 
    if($value==$prev) 
    { 
     $tt[$key] = $tt[$p]; 
    }else 
    { 
     $tt[$key] = $ii; 
    } 
    $prev = $value; 
    $p = $key; 

} 

echo '<pre>'; 
print_r($tt); 

輸出

Array 
(
    [C] => 1 
    [B] => 1 
    [G] => 1 
    [F] => 4 
    [A] => 5 
    [D] => 6 
    [E] => 7 
    [H] => 7 
    [I] => 9 
    [K] => 10 
    [J] => 10 
) 
+1

我做了它,但我不得不使用3的foreach .. 。投票或你的答案,因爲它是最優化的。謝謝! – csotelo

2

按值分組,然後使用krsort從最大到最小排序(注意:如果您的初始數組已經排序,則可以跳過krsort)。通過遍歷分組結果並按照每組中的元素數增加分數來對結果進行評分。

$r = array (
    'C' => '11.00.00', 
    'B' => '11.00.00', 
    'G' => '11.00.00', 
    'F' => '10.02.00', 
    'A' => '10.00.00', 
    'D' => '09.00.00', 
    'E' => '08.00.00', 
    'H' => '08.00.00', 
    'I' => '07.00.00', 
    'K' => '06.00.00', 
    'J' => '06.00.00', 
); 

$grouped_results = array(); 

foreach($r as $k => $v) { 
    $grouped_results[$v][] = $k; 
} 

krsort($grouped_results); 
$score = 1;  
$scores = array(); 

foreach($grouped_results as $group) { 
    foreach($group as $result) { 
     $scores[$result] = $score; 
    } 

    $score += count($group); 
} 

print_r($scores); 

輸出

Array 
(
    [C] => 1 
    [B] => 1 
    [G] => 1 
    [F] => 4 
    [A] => 5 
    [D] => 6 
    [E] => 7 
    [H] => 7 
    [I] => 9 
    [K] => 10 
    [J] => 10 
) 
+0

感謝您的幫助 – csotelo