首先,您必须对数组进行排序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";