まず、配列をで並べ替える必要がありますasort
(インデックスと値の関連付けを維持し、値で並べ替えるため)。
asort($yourArray);
次に、配列を並べ替えるときに、価格と名前を分離できます。
$names = array_keys($yourArray);
$prices = array_values($yourArray);
この時点で、ラベルと価格を含む2つの数値インデックス付き配列があり、これら2つの配列は同期されています。
最後に、0から配列の長さ(そのうちの1つ、同じサイズ)までループして、プロセスを作成する必要があります。
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";