在PHP中使用其他文本包围字符串的一些方法?

Jus*_*tin 1 javascript php arrays string text

我有以下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;
}
Run Code Online (Sandbox Code Playgroud)

这是我在我的应用程序中使用来从数组数据创建选择框的东西.我刚刚添加了4个新的$ cfg变量,用于在选择框的键和值之前或之后添加字符串.因此,例如,如果我的下拉列表默认情况下看起来像"A,B,C",我可以通过:

$cfg['beforeValue'] = 'Select ';
$cfg['afterValue'] = ' now!';
Run Code Online (Sandbox Code Playgroud)

并获得"现在选择一个!,现在选择B!现在选择C!"

所以这很好用,但我想知道PHP中是否有某种方法可以在一行中完成这一点而不是两行.我认为必须有一种特殊的方法来做到这一点.

dec*_*eze 6

首先,用这个简化可怕的代码:

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

不需要所有isset重复的键名,一个简单的数组联合就可以了.

其次,您可以使用以下内容sprintf:

$cfg['surroundingValue'] = 'Select %s now!';
echo sprintf($cfg['surroundingValue'], $valueInTheMiddle);
Run Code Online (Sandbox Code Playgroud)