2011-08-08 95 views
0

我有存儲在mysql數據庫中的輪詢結果。
我嘗試輸出結果很好,但現在我嘗試按降序(最高的第一個)和正確的名稱得到結果。現在的輸出是這樣的:替換與另一個數組匹配的數組鍵(foreach循環)

print "<pre>"; 
print_r(array_count_values($array_a)); 
print "</pre>"; 

//OUTPUTS first key is the poll option and second is how much it was voted for. 
[4] => 1 
[12] => 17 
[2] => 3 
[6] => 42 
[8] => 6 
[16] => 5 
[3] => 30 
[18] => 1 
[1] => 5 

首先,我想用一個名字來代替數字。這是我卡住的地方。 str_replace不起作用,因爲它會替換所有匹配的數字,但不是確切的數字。 foreach循環正確,但有17個數字要被替換,所以我喜歡用數組來獲取它們,但不知道如何。

foreach($array_a as &$value){ 
    if($value==1){ 
     $value = "opt1"; 
    } 
} 

$patterns = array(); 
$patterns[0] = '1'; 
$patterns[1] = '2'; 
$patterns[2] = '3'; 
$patterns[3] = '4'; 

$replacements = array(); 
$replacements[0] = 'Car'; 
$replacements[1] = 'Boat'; 
$replacements[2] = 'Bike'; 
$replacements[3] = 'Photo'; 

我喜歡的結果來實現:

//OUTPUT 
[Car] => 30 
[Bike] => 25 
[Paint] => 10 
[Goat] => 5 
[Photo] => 3 
+0

你想達到什麼結果?向我們展示所需的陣列。 –

+0

我已將它添加到原始帖子 – Rob

+0

你可以嘗試使用[asph](http://www.php.net/manual/en/function.asort.php)php – linuxeasy

回答

0

如何:

$replacements = array(); 
$replacements[2] = 'Car'; // your key should be the key of $array_a here and 
$replacements[1] = 'Boat'; // value should be the key you want to be used 
$replacements[5] = 'Bike'; 
$replacements[3] = 'Photo'; 


$finalPollArray = array(); 

foreach($replacements as $key => $value) 
{ 
    $finalPollArray[$value] = $array_a[$key]; 
} 

$finalPollArray = asort($finalPollArray) 

print "<pre>"; 
print_r($finalPollArray); 
print "</pre>"; 

一個非常實際的例子是:

$poll[5] = 13; 
$poll[6] = 12; 
$poll[3] = 10; 
$poll[12] = 7; 
$poll[8] = 6; 
$poll[1] = 5; 
$poll[7] = 5; 
$poll[16] = 5; 
$poll[13] = 4; 

// with this code I get the following output 
$replacements = array(); 
$replacements[5] = 'Car'; 

$finalPollArrayA = array(); 

foreach($replacements as $key => $value) 
{ 
    $finalPollArrayA[$value] = $poll[$key]; 
} 

print "<pre>"; 
print_r($finalPollArrayA); 
print "</pre>"; 

並輸出我:

Array 
(
    [Car] => 13 
) 

是否如預期的那樣?

+0

我認爲'opt'。($ key + 1),Rob需要0 => 1,1 => 2,等等。 – J0HN

+0

謝謝,我剛剛錯過了asort函數,現在應該按預期輸出! – linuxeasy

+0

這看起來應該很好,但我忘了指出'opt'這個名字是在民意調查中詢問的事物的標記名稱。我已更新原始帖子。 – Rob

相關問題