我在网站上工作,应该是比较产品。所以我已经到达了下面的数组
Array ( [iPhone 4 8GB Black] => 319 [iPhone 4S] => 449 [iphone 5] => 529 ) 数组的键是产品名称,数组的值是价格。现在我想把这个数组转换成如下语句
IPhone48 8GB黑色是最便宜的!
iPhone 48 4S的黑色比iPhone4S便宜130 4S(计算:449-319)。
iPhone 48 is的黑色比iPhone5便宜210 is(计算:529-319)。
IPhone4S比iPhone 5便宜80£(计算:529-449)。
IPhone5是你选择的列表中最贵的产品。
请告诉我如何从数组中输出这些语句。在比较方面,你建议用这个数组做一些其他的事情也会很好。谢谢。
发布于 2013-03-05 19:26:31
首先,您必须使用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";https://stackoverflow.com/questions/15222347
复制相似问题