我正在网站上工作,假设要比较产品。所以我已经达到了以下数组
Array ( [iPhone 4 8GB Black] => 319 [iPhone 4S] => 449 [iphone 5] => 529 )
数组的键是产品名称,数组的值是价格。现在我想把这个数组翻译成像
这样的语句iphone 4 8GB黑色最便宜!
iPhone 48GB黑色比英特尔4S便宜130英镑(计算:449-319)。
iPhone 48GB黑色比iphone 5便宜210英镑(计算:529-319)。
iPhone 4S比iPhone 5便宜80英镑(计算:529-449)。iphone 5是您所选列表中最贵的产品。
请帮我介绍如何从数组中输出这些语句。你建议在比较方面用这个数组做其他事情也很棒。谢谢。
答案 0 :(得分:1)
首先,您必须使用asort
对数组进行排序(为了保持索引与值之间的关联,并对值进行排序)。
asort($yourArray);
然后,在对数组进行排序时,您可以隔离价格和名称。
$names = array_keys($yourArray);
$prices = array_values($yourArray);
此时你有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";