PHP:文本的替代值与正则表达式或浸渍表达阵列

问题描述:

下面是我的阵列,在这里我想和喜欢完整路径替换[image] => 201310171708033183470.jpgPHP:文本的替代值与正则表达式或浸渍表达阵列

[image] => http://localhost/website/uploads/201310171708033183470.jpg 

我想给一个完整路径的所有图像名称如下:

[images] => Array 
      (
       [0] => Array 
        (
         [id] => 12 
         [product_id] => 9 
         [image] => 201310171708033183470.jpg 
         [order] => 1 
         [status] => 1 
         [created] => 2013-10-17 17:08:03 
         [modified] => 2013-10-17 17:08:03 
        ) 

       [1] => Array 
        (
         [id] => 11 
         [product_id] => 9 
         [image] => 201310171514176427410.jpg 
         [order] => 1 
         [status] => 1 
         [created] => 2013-10-17 15:14:17 
         [modified] => 2013-10-17 15:14:17 
        ) 

       [2] => Array 
        (
         [id] => 10 
         [product_id] => 9 
         [image] => 201310171514066591090.jpg 
         [order] => 1 
         [status] => 1 
         [created] => 2013-10-17 15:14:06 
         [modified] => 2013-10-17 15:14:06 
        ) 

       [3] => Array 
        (
         [id] => 9 
         [product_id] => 9 
         [image] => 201310171513591880300.jpg 
         [order] => 1 
         [status] => 1 
         [created] => 2013-10-17 15:13:59 
         [modified] => 2013-10-17 15:13:59 
        ) 

      ) 

哪种做法最快最优化?

+0

是静态路径吗? – abc123

+0

@ abc123:是的路径将始终相同 –

必须使用&用foreach使用变量本身,而不是变量的副本。

foreach($products as &$product) { 
    $product['image'] = 'http://localhost/website/uploads/' . $product['image']; 
} 

的另一种方法是使用array_map:

function addpath($product){ 
    $product['image'] = 'http://localhost/website/uploads/' . $product['image']; 
    return $product; 
} 
$products = array_map('addpath', $products); 

或者array_walk:

function addpath(&$product) { 
    $product['image'] = 'http://localhost/website/uploads/' . $product['image']; 
} 
array_walk($products, 'addpath'); 

为了您的测试序列中,第一种方式似乎更快。对于一个巨大的数组(70000项),您可以获得foreach < array_walk < array_map,比其他两个foreach约快1.5倍。

希望它可以帮助,

foreach($images as $k=>$image){ 

     $image['image'] = 'http://localhost/website/uploads/'.$image['image']; 
    }