Php:将字符串连接到所有数组项中

时间:2012-03-24 07:53:44

标签: php arrays

我有this PHP代码段:

<?php
  $colors = array('red','green','blue');
  foreach ($colors as &$item)
  {
    $item = 'color-'.$item;
  }
  print_r($colors);
?>  

输出

Array
(
  [0] => color-red
  [1] => color-green
  [2] => color-blue
)

解决方案更简单吗?

(某些数组php函数,如array_insert_before_all_items($colors,"color-"))?

由于

6 个答案:

答案 0 :(得分:12)

方法array_walk将允许您通过回调“访问”数组中的每个项目。使用php 5.3,您甚至可以使用anonymous functions

Pre PHP 5.3版本:

function carPrefix(&$value,$key) {
  $value="car-$value";
}
array_walk($colors,"carPrefix");
print_r($colors);

较新的匿名函数版本:

array_walk($colors, function (&$value, $key) {
   $value="car-$value";
});
print_r($colors);

答案 1 :(得分:2)

对于旧版本的php,这应该可行

select 'count' as is_active,
    sum(is_active = 0) as count_0,
    sum(is_active = 1) as count_1
from t;

结果:

foreach ($colors as $key => $value) {
$colors[$key] = 'car-'.$value; //concatinate your existing array with new one
}
print_r($sbosId);

答案 2 :(得分:1)

试试这个:

$colors = array('red','green','blue');

function prefix_car( &$item ) {
    $item = "car-{$item}";
}

array_walk( $colors, 'prefix_car');

它应该像你做的那样工作,尽管有点严厉; array_walk比手动循环更灵活。

答案 3 :(得分:0)

$colors = array('red','green','blue');

$prefix = "car-";

$color_flat = $prefix . implode("::" . $prefix,$colors);

$colors = explode("::",$color_flat);

print_r($colors);

答案 4 :(得分:0)

使用array_map的替代示例:http://php.net/manual/en/function.array-map.php

<强> PHP:

$colors = array('red','green','blue');

$result = array_map(function($color) {
    return "color-$color";
}, $colors);

输出($result):

array(
    'color-red',
    'color-green',
    'color-blue'
)

答案 5 :(得分:0)

$colors = array('red','green','blue');
$colors = substr_replace($colors, 'color-', 0, 0);
print_r($colors);