数组元素包装所有元素

Val*_*Val 10 php arrays

我想用类似的东西包装数组的所有元素,但我不想要很多行或foreach循环

$links = array('london','new york','paris');

// the outcome should be 

<a href="#london">london</a>
<a href="#new york">new york</a>
<a href="#paris">paris</a>
Run Code Online (Sandbox Code Playgroud)

nic*_*ckb 28

array_map怎么

$links   = array('london', 'new york', 'paris');
$wrapped = array_map(
   function ($el) {
      return "<a href=\"#{$el}\">{$el}</a>";
   },
   $links
);
Run Code Online (Sandbox Code Playgroud)

演示(点击源代码)

没有PHP> 5.3,你不能使用lambda函数,所以你需要这样的东西:

function wrap_those_links($el)  { 
      return "<a href=\"#{$el}\">{$el}</a>"; 
}

$links   = array('london', 'new york', 'paris');
$wrapped = array_map('wrap_those_links', $links);
Run Code Online (Sandbox Code Playgroud)

PHP 5.2演示(再次点击Source)

  • 或者`create_function` (2认同)

Ed *_*eal 7

尝试 join('\n', array_map(function($a) { return "<a href=\"#$a\",>$a<\\a>";}, $links));

  • ...或者因为他没有使用命名函数"implode",而是使用别名"join",并且没有以易读的方式格式化答案,或者提供了有关建议限制的解释(PHP 5) > = 5.3).在自我记录方面,Implode更加含蓄. (2认同)