将前缀添加到数组的特定值

时间:2018-01-18 15:22:27

标签: php arrays foreach

我正在尝试为数组中的值添加url前缀:

例如,数组$cars

当前数组:

     array (size=3)
      0 => 
        array (size=3)
          'id' => string '1' (length=1)
          'image' => string '1.jpg' (length=5)
          'car' => string 'bmw' (length=12)
      1 => 
        array (size=3)
          'id' => string '2' (length=1)
          'image' => string '2.jpg' (length=5)
          'car' => string 'mercedes' (length=17)
      2 => 
        array (size=3)
          'id' => string '3' (length=1)
          'image' => string '3.jpg' (length=5)
          'car' => string 'bentley' (length=9)

我想在图片密钥中添加前缀。

结果应如下所示:

array (size=3)
  0 => 
    array (size=3)
      'id' => string '1' (length=1)
      'image' => string 'http://cars.com/1.jpg' (length=5)
      'car' => string 'bmw' (length=12)
  1 => 
    array (size=3)
      'id' => string '2' (length=1)
      'image' => string 'http://cars.com/2.jpg' (length=5)
      'car' => string 'mercedes' (length=17)
  2 => 
    array (size=3)
      'id' => string '3' (length=1)
      'image' => string 'http://cars.com/3.jpg' (length=5)
      'car' => string 'bentley' (length=9)

3 个答案:

答案 0 :(得分:1)

只需在数组上循环。 Sandbox with tests

使用foreach:

foreach ($arr as $i => $a) {
   $arr[$i]['image'] = 'http://cars.com/' . $arr[$i]['image'];
}

使用foreach参考:

foreach ($arr as &$a) {
   $a['image'] = 'http://cars.com/' . $a['image'];
}

用于:

for ($i = 0; $i < count($arr); $i++) {
   $arr[$i]['image'] = 'http://cars.com/' . $arr[$i]['image'];
}

使用array_walk:

array_walk($arr3,  function(&$v) { 
    $v['image'] = 'http://cars.com/' . $v['image'];
});

使用while:

$i = count($arr) - 1;
while ($i > 0) {
   $arr[$i]['image'] = 'http://cars.com/' . $arr[$i]['image'];
   $i--;
}

答案 1 :(得分:0)

假设您的阵列可能被称为$ cars,那么......

foreach ($cars AS $key => $car) {
  $cars[$key]['image'] = 'http://cars.com/' . $car['image'];
}

答案 2 :(得分:0)

您可以使用foreach(或for)循环数组,或者您可以使用array_walk函数逐步遍历数组并更改每个项目:

array_walk($cars, function(&$item) {
    $item['image'] = "http://cars.com/".$item['image'];
});