2013-03-05 23 views
0

我在網站上工作,假設比較產品。所以我已經達到了以下陣列如何在PHP中將數組信息轉換爲語句?

Array ([iPhone 4 8GB Black] => 319 [iPhone 4S] => 449 [iphone 5] => 529) 

該數組的關鍵是產品名稱和數組的值是價格。現在我想把這個數組翻譯成像

iphone 4 8GB黑色是最便宜的!

iPhone 48GB黑色比iphone 4S便宜130英鎊(計算:449-319)。

iPhone 48GB黑色是£210(計算:529-319)比iphone便宜5.

iPhone 4S爲80£(計算:529-449)比iphone便宜5.

iphone 5是您選擇的清單中最昂貴的產品。

請幫助我如何從數組中輸出這些語句。你在這個數組中做比較的建議也很好。謝謝。

+0

我還沒有嘗試過任何yet.so到目前爲止,我只能輸出:iphone 4 8GB成本319. iPhone 4S使用foreach循環花費449美元等等。 – 2013-03-05 11:21:07

+0

這是一個簡單的'for'循環和一些'if',我也認爲它應該是學習PHP的好習慣,並且會建議您嘗試單獨完成,以查閱'for'和'if'的PHP文檔。 – Naryl 2013-03-05 11:28:24

+0

輸出將具有'sum(1..l-1)+ 2'行,即'(l-1)*(1-2)/ 2 + 2',其中'l'是陣列的長度。因此,對於10個產品列表,這將是38行。你確定你要這麼做嗎? – Passerby 2013-03-05 11:35:44

回答

1

首先,您必須使用asort(爲了保持索引和值之間的關聯以及對值進行排序)對數組進行排序。

asort($yourArray); 

然後,因爲你的數組是排序的,你可以分離價格和名稱。

$names = array_keys($yourArray); 
$prices = array_values($yourArray); 

此時您擁有一個包含標籤,並且價格2數字索引數組和這些2個數組是同步的。

最後,你只需要循環,從0到您的陣列(其中之一,它的大小相同)的長度,並提出您的過程:

for($i = 0 ; $i < count($names) ; $i++) 
{ 
    if ($i == 0) 
    { 
     // First product -> cheapest 
     echo "The product " . $names[$i] . " is cheapest"; 
    } 
    else if ($i == (count($names) - 1)) 
    { 
     // Last product, the most expensive 
     echo "The product " . $names[$i] . " is the most expensive product of the list"; 
    } 
    else 
    { 
     // calculate the diff between current product and first product 
     $diff = $price[$i] - $price[0]; 
     echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[0]; 
    } 
} 

這個例子讓所有比較的第一款產品。

如果你需要的所有組合,它是一個小更配合物,你必須做出一個雙循環:

// Hard print the first product 
echo "The product " . $names[0] . " is the cheapest"; 

// Make all possible comparisions 
for($j = 0 ; $j < (count($names) - 1) ; $j++) 
{ 
    for($i = ($j+1) ; $i < count($names) ; $i++) 
    { 
     // calculate the diff between current product and first product 
     $diff = $price[$i] - $price[$j]; 
     echo "The product " . $names[$i] . " is " . $diff . " more expensive than " . $names[$j]; 
    } 
} 

// Hard print the last product 
echo "The product " . $name[count($names) - 1] . " is the more expensive"; 
+0

謝謝!我正在尋找這樣的事情。你太棒了!! – 2013-03-05 11:41:09

+0

事實上,我的解決方案只是簡單地將所有產品與第一個產品進行比較。如果你想做所有的比較組合,你只需要把這個循環包裝到一個父循環(2級循環)中,並且稍微測試一下測試部分。祝你好運 – MatRt 2013-03-05 11:47:05

+0

增加了第二位代碼 – MatRt 2013-03-05 12:36:30