0

有没有办法在语句之后编写更少的代码(分解)。在我的情况下,我有 webform_client_form_AKEY ,其中 AKEY var 发生变化,我的 var 在 uri 中传递(?C= = 1 ...)。谢谢

switch ($form_id)
{
case 'webform_client_form_9944':
    $form['#action'] = url('section/client-tool-box/appointment?c=1');          
    break;
case 'webform_client_form_9883':
    $form['#action'] = url('section/client-tool-box/appointment?c=2'); 
    break;
case 'webform_client_form_9884':
    $form['#action'] = url('section/client-tool-box/appointment?c=3');          
    break;
...
}
4

7 回答 7

3

使用“字典”方法:

$array = array(
    "webform_client_form_9944" => "1",
    "webform_client_form_9883" => "2",
    "webform_client_form_9884" => "3"
);

if (array_key_exists($array, $form_id))
    $form['#action'] = url('section/client-tool-box/appointment?c=' . $array[$form_id]);
else
    $form['#action'] = ""; // default
于 2012-09-05T09:57:48.867 回答
2
$urls = array(
  'webform_client_form_9944' => 'section/client-tool-box/appointment?c=1',
  'webform_client_form_9883' => 'section/client-tool-box/appointment?c=2',
   ...
);

$form['#action'] = url($urls[$form_id]);
于 2012-09-05T09:57:26.573 回答
0

如何将“form_id”到“c”映射保留在数组中?我猜,这使得维护变得更加容易。此外,没有更多重复的代码:

<?php
$form_id = 'webform_client_form_9944';

$forms = array(
    '9944' => '1',
    '9883' => '2',
    '9884' => '3'
);

$id = str_replace('webform_client_form_', '', $form_id);

if (isset ($forms[$id])) {
    $form['#action'] = url('section/client-tool-box/appointment?c=3');
}
于 2012-09-05T10:01:06.273 回答
0

我不认为在这里编写更少的代码实际上很重要。但我想如果你抽象出数据,代码会更容易维护:

// Untested
$id_to_c = array(
    9944 => 1,
    9883 => 2,
    9884 => 3,
);
if( preg_match('^webform_client_form_(\\d)$', $form_id, $matches) ){
    if( array_keys_exists($matches[1], $id_to_c) ){
        $form['#action'] = url('section/client-tool-box/appointment?c=' . rawurlencode($id_to_c[$matches[1]]));   
    }
}
于 2012-09-05T10:01:23.273 回答
0

您可以执行以下操作:

$formid = end(explode('_', $form_id));
$map = array(9944=>1, 9883=>2, 9844=>3, ...);

$form['#action'] = url("section/client-tool-box/appointment?c={$map['webform_client_form_'.$map[$formid]}");
于 2012-09-05T10:02:18.083 回答
0

Ya :

$cat = 0; //0 : default cat
switch ($form_id) {
   case 'webform_client_form_9944': $cat = 1; break;
   case 'webform_client_form_9883': $cat = 2; break;
   case 'webform_client_form_9884': $cat = 3; break;
   ...
}
$form['#action'] = url('section/client-tool-box/appointment?c='.$cat);
于 2012-09-05T09:56:39.127 回答
0

你可以试试这种方式

$form_id= 'webform_client_form_9944';
$cons = 'webform_client_form_';

switch($form_id){
    case $cons.'9944':
        $c = 1;
        break;
    case $cons.'9883':
        $c = 2;
        break;
}
$form['#action'] = url('section/client-tool-box/appointment?c='.$c);
于 2012-09-05T09:59:12.657 回答