从三个不同的数组中获取值

时间:2015-07-24 11:31:58

标签: php arrays codeigniter

我有三个不同的数组

price = Array
(
    [0] => 200
    [1] => 300
    [2] => 400
    [3] => 500
)

package = Array
(
    [0] => 100040
    [1] => 100041
    [2] => 100042
    [3] => 100043
)

NoOfClients =Array
(
    [0] => 100
    [1] => 200
    [2] => 400
    [3] => 750
)

需要根据NoOfClients获取包裹和价格。 示例:如果我的客户端数量是350,那么我的包是100042,价格= 400。 为了更好地理解下面我展示了一个if else条件

clients = 350;
if(clients <= NoOfClients[0]){

plan = 100040
price = 200

}elseif(clients > NoOfClients[0] and clients <= NoOfClients[1]){

plan = 100041
price = 300

}elseif(clients > NoOfClients[1] and $clients <= NoOfClients[2]){

plan = 100042
price = 400

}else{

plan = 100043
price = 500

}

我的问题是我将如何根据三个不同的数组获得动态结果(计划和价格)并传递客户端数量。请帮忙

3 个答案:

答案 0 :(得分:0)

试试这个。如果您按升序给出数组值,就像您在此处给出的那样,那么它正常工作

$clients= 10;
$price = array(200, 300, 400, 500);
$package = array(100040, 100041, 100042, 100043);
$NoOfClients = array(100, 200, 400, 750);

if($clients<=$NoOfClients[0])
{
    $tempprice=$price[0];
    $temppackage=$package[0];
}
else
{
    for($i=0;$i<count($NoOfClients);$i++)
    {
        if($i+1<=count($NoOfClients) && !$clients>=$NoOfClients[$i] && $clients<=$NoOfClients[$i+1])
        {
            $tempprice=$price[$i+1];
            $temppackage=$package[$i+1];
            break;
        }
        else
        {
            $tempprice=$price[count($NoOfClients)-1];
            $temppackage=$package[count($NoOfClients)-1];
        }
    }
}

echo '<b>Price:</b> '.$tempprice.'<br/><b>Package:</b> '.$temppackage;

答案 1 :(得分:0)

如果您在数组中仅使用4个值,那么您可以使用您自己使用的循环获得价格和包的值,只需进行少量更改

clients = 350;
if(clients <= NoOfClients[0]){

plan = package[0];
price = price[0];

}elseif(clients > NoOfClients[0] and clients <= NoOfClients[1]){

plan =  package[1];
price = price[1];

}elseif(clients > NoOfClients[1] and $clients <= NoOfClients[2]){

plan =  package[2];
price = price[2];

}else{

plan =  package[3];
price = price[3];

}

答案 2 :(得分:0)

$clients = 10;

$i = -1;
foreach($NoOfClients as $item) {
   $i++;
   if ($clients < $item) break;
}

echo $plan = $package[$i];
echo $price = $price[$i];