【问题标题】:Some way to surround string with other text in PHP?用PHP中的其他文本包围字符串的某种方式?
【发布时间】:2012-08-15 15:52:36
【问题描述】:

我有以下 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!';

然后得到“现在选择 A!,现在选择 B!,现在选择 C!”

所以这很好用,但我想知道 PHP 中是否有某种方法可以用一行而不是两行来实现这一点。我想一定有一种特殊的方法可以做到这一点。

【问题讨论】:

  • 喜欢sprintf() 吗? sprintf("Select %s now!", $cfg['methodValue'])

标签: php javascript arrays string text


【解决方案1】:

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

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);

【讨论】:

  • 我以前使用过数组合并,但我从来没有想过在这样的地方使用它。所以谢谢你。如果我错了,请纠正我,但 $cfg += array(//defaultconditions) 与 $cfg = $cfg + array(//defaultconditions) 相同,与 array_merge($cfg, array(//defaultconditions) 相同. 基本上,如果键存在于 $cfg 中,那将是生成的 $cfg 变量中使用的值,否则,将使用默认值。
  • @Justin 在这种情况下,是的,都是一样的。 array_merge+ 仅在处理数字索引方面有所不同。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 2016-02-07
  • 2021-11-20
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多