array_intersect具有多维数组和非多维数组

时间:2015-06-06 16:13:09

标签: php

我有以下不同字体样式的数组:

Array
(
    [lightCuts] => Array (
            [0] => light
            [1] => light-italic
            [2] => light-condensed
            [3] => light-leftside
            [4] => light-extended
        )


    [regulaCuts] => Array (
            [0] => regular
            [1] => regular-italic
            [2] => regular-condensed
        )

    [mediumCuts] => Array (
            [0] => medium
            [1] => medium-italic
            [2] => medium-condensed
        )

    [boldCuts] => Array (
            [0] => bold
            [1] => bold-italic
            [2] => bold-condensed
        )

)

应该在一个小购物车中使用。每种款式的价格为50美元。如果一个人从相同的重量购买两个或更多(f.e 3来自lightCuts这3个是更干净的)。

让我们说选择“光”,“轻斜”,“中”。我如何得到输出“轻和轻 - 斜成本30美元和中等成本50美元”。我想我需要array_intersect和count(),但无法弄清楚如何。

$availableCuts = array(
"lightCuts" => array("light","light-italic","light-condensed","light-leftside","light-extended"),
"regulaCuts" => array("regular","regular-italic","regular-condensed"),
"mediumCuts" => array("medium","medium-italic","medium-condensed"),
"boldCuts" => array("bold","bold-italic","bold-condensed"),
);

$selectedCuts = array("light","light-italic","medium"); 

我不坚持使用这种阵列组合。

1 个答案:

答案 0 :(得分:0)

<?php

$selectedArr = array();
foreach($availableCuts as $item) 
{
    if ($selected = array_intersect($item, $selectedCuts)) 
    {
        if (count($selected) == 1) $cost = 'cost 50$';
        elseif (count($selected) > 1) $cost = 'costs 30$';

        $selectedArr[] = implode(" and ", $selected) . " $cost";
    }
}

echo implode(" and ", $selectedArr);
// echoes "light and light-italic cost 30$ and medium costs 50$"