将Hardcoded if语句减少为更动态

时间:2015-03-27 12:29:11

标签: php if-statement

我有一个单选按钮,可以在无限量的行中选择,因为每次第一个完成时它会添加一个新行,然后用户选择他们想要哪个主要数字,将其设置为值“1”或“2”等。

我的问题是如果用户在哪里输入超过8个电话号码我的代码将会过时我想知道最好的方法是:

if ($Details['MakePrimary'] == 1){
    $Customer->Code = $Details['phoneNumber'][0]['Code']; 
    $Customer->Number = $Details['phoneNumber'][0]['mainNumber']; 
} else if ($Details['MakePrimary'] == 2){
    $Customer->Code = $Details['phoneNumber'][1]['Code']; 
    $Customer->Number = $Details['phoneNumber'][1]['mainNumber']; 
} else if ($paymentDetails['MakePrimary'] == 3){
    $Customer->StdCode = $Details['phoneNumber'][2]['Code']; 
    $Customer->Number = $Details['phoneNumber'][2]['mainNumber'];   
} else if ($Details['MakePrimary'] == 4){
    $Customer->Code = $Details['phoneNumber'][3]['Code']; 
    $Customer->Number = $Details['phoneNumber'][3]['mainNumber'];
} else if ($paymentDetails['MakePrimary'] == 5){
    $Customer->Code = $Details['phoneNumber'][4]['Code']; 
    $Customer->Number = $Details['phoneNumber'][4]['mainNumber']; 
} else if ($Details['MakePrimary'] == 6){
    $Customer->Code = $Details['phoneNumber'][5]['Code']; 
    $Customer->Number = $Details['phoneNumber'][5]['mainNumber'];   
} else if ($Details['MakePrimary'] == 7){
    $Customer->Code = $Details['phoneNumber'][6]['Code']; 
    $Customer->Number = $Details['phoneNumber'][6]['mainNumber'];   
} else if ($Details['MakePrimary'] == 8){
    $Customer->Code = $Details['phoneNumber'][7]['Code']; 
    $Customer->Number = $Details['phoneNumber'][7]['mainNumber'];                               
} else {
    $Customer->Code = $Details['phoneNumber'][8]['Code']; 
    $Customer->Number = $Details['phoneNumber'][8]['mainNumber'];
}                       

2 个答案:

答案 0 :(得分:2)

你应该试试这个:

$index = $paymentDetails['MakePrimary'] - 1;
$voipCustomer->StdCode = $paymentDetails['phoneNumber'][$index]['stdCode'];
$voipCustomer->Number = $paymentDetails['phoneNumber'][$index]['mainNumber']; 

答案 1 :(得分:0)

<?php

 $Customer->Code = $Details['phoneNumber'][$Details['MakePrimary']-1]['Code']; 
 $Customer->Number = $Details['phoneNumber'][$Details['MakePrimary']-1]['mainNumber'];