2012-08-15 26 views
1

我有以下PHP函數:用PHP中的其他文本包圍字符串的一些方法?

public function createOptions($options, $cfg=array()) { 
     $cfg['methodKey'] = isset($cfg['methodKey']) ? $cfg['methodKey'] : 'getId'; 
     $cfg['methodValue'] = isset($cfg['methodValue']) ? $cfg['methodValue'] : 'getName'; 
     $cfg['beforeKey'] = isset($cfg['beforeKey']) ? $cfg['beforeKey'] : ''; 
     $cfg['beforeValue'] = isset($cfg['beforeValue']) ? $cfg['beforeValue'] : ''; 
     $cfg['afterKey'] = isset($cfg['afterKey']) ? $cfg['afterKey'] : ''; 
     $cfg['afterValue'] = isset($cfg['afterValue']) ? $cfg['afterValue'] : ''; 
     $array = array(); 
     foreach ($options as $obj) { 
      $array[$cfg['beforeKey'] . $obj->$cfg['methodKey']() . $cfg['afterKey']] = $cfg['beforeValue'] . $obj->$cfg['methodValue']() . $cfg['afterValue']; 
     } 
     return $array; 
} 

這件事情,我用在我的應用程序來創建數組數據選擇框。我最近添加了4個新的$ cfg變量,用於在選擇框的鍵和值之前或之後添加字符串。因此,舉例來說,如果我的下拉列表看起來像「A,B,C」在默認情況下,我可以通過:

$cfg['beforeValue'] = 'Select '; 
$cfg['afterValue'] = ' now!'; 

,並得到「選擇現在!選擇B現在!選擇C吧!」

所以這工作得很好,但我想知道是否有某種方式在PHP中完成這一行在一行發言而不是兩個。我認爲必須有一種特殊的方式來做到這一點。

+1

用一樣['sprintf的()'](http://us.php.net/manual/en/function.sprintf.php)? 'sprintf(「Select%s now!」,$ cfg ['methodValue'])' – 2012-08-15 15:56:34

回答

6

首先,簡化了那場可怕的代碼如下:

public function createOptions($options, array $cfg = array()) { 
    $cfg += array(
     'methodKey' => 'getId', 
     'methodValue' => 'getName', 
     ... 
    ); 

無需所有isset和重複鍵名,一個簡單的數組工會就行了。

其次,你可以使用類似sprintf

$cfg['surroundingValue'] = 'Select %s now!'; 
echo sprintf($cfg['surroundingValue'], $valueInTheMiddle); 
+0

這段代碼是做什麼的$ cfg + = array('? – Jocelyn 2012-08-15 16:04:47

+0

Array union:http://www.php.net/ manual/en/language.operators.array.php – deceze 2012-08-15 16:05:54

+0

我之前使用過數組合並,但是我從來沒有想過在這樣的地方使用它,所以謝謝你的支持, 糾正我,如果我錯了,但是$ cfg + = array(// defaultconditions)與$ cfg = $ cfg + array(// defaultconditions)是一樣的array_merge($ cfg,array(// defaultconditions) 基本上如果key存在在$ cfg中,這將是所得到的$ cfg變量中使用的值,否則將使用默認值 – Justin 2012-08-15 16:09:15

相關問題