如何在php中将数组信息转换成语句


how to translate array information into statement in php?

我在网站上工作,假设比较产品。所以我已经到达了下面这个数组

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

数组的键是产品名称,数组的值是价格。现在我想把这个数组转换成像

这样的语句iphone 4 8GB黑色最便宜!

iPhone 48GB Black比iPhone 4S便宜130英镑(计算:449-319)

iPhone 48GB Black比iPhone 5便宜210英镑(计算:529-319)

iPhone 4S比iPhone 5便宜80英镑(计算:529-449)

iphone 5是你选择列表中最贵的产品。

请告诉我如何从数组输出这些语句。你的建议在比较方面对这个数组做一些其他的事情也会很好。谢谢你。

首先,您必须使用asort对数组进行排序(为了保持索引和值之间的关联,并对值进行排序)。

asort($yourArray);

然后,在数组排序后,可以分离价格和名称。

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

此时,您有两个数字索引数组,其中包含您的标签和价格,并且这两个数组是同步的。

最后,你只需要从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";