【问题标题】:Is there a reliable PHP one liner to suffix/prefix array values? [duplicate]是否有可靠的 PHP 单行器来为数组值添加后缀/前缀? [复制]
【发布时间】:2016-09-23 09:11:42
【问题描述】:

我需要给数组值添加后缀,这实际上是一个标签 CSS,所以我需要给一个数组添加后缀 :hover,另一个添加后缀 :focus

$elements = array('.one','.two','.three');

想要的新数组

$helements = array('.one:hover','.two:hover','.three:hover');
$felements = array('.one:focus','.two:focus','.three:focus');

我知道我可以使用循环来完成,但问题是,是否有一个快速的单线器来解决这个问题?

【问题讨论】:

  • 数组的每个元素总是相同的值?
  • @Napolux,是的,它将是 :hover 或 :focus 后缀
  • 你可以使用 array_map 甚至 array_walk 来做这个。
  • 您为什么要寻找“快速oneliner”?你认为它会比普通的旧循环更好或更快吗?
  • 您可以使用正则表达式。喜欢Regex to Add a postfix to each item of a PHP array

标签: php arrays loops


【解决方案1】:
$newelements = array_map(function($x){ return $x . ':hover'; }, $elements);

【讨论】:

    【解决方案2】:

    您可以更改数组本身(如我的解决方案)或创建一个新数组,如in the other answer。你的选择。 ;)

    您可以只传递$item 作为参考,以便直接更改原始数组。

    $array = ["test1", "test2", "test3"];
    array_walk($array,function(&$item) {$item .= ':hover';});
    

    结果是:

    var_dump($array);
    
    array(3) {
      [0]=>
      string(11) "test1:hover"
      [1]=>
      string(11) "test2:hover"
      [2]=>
      string(11) "test3:hover"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2021-04-26
      • 2013-02-04
      • 2017-12-02
      • 1970-01-01
      • 2011-11-28
      相关资源
      最近更新 更多