下面是我的数组,我希望将[image] => 201310171708033183470.jpg
替换为完整路径,如:
[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 :(得分:1)
希望它有所帮助,
foreach($images as $k=>$image ){
$image['image'] = 'http://localhost/website/uploads/'.$image['image'];
}
答案 1 :(得分:1)
你必须使用&使用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,其速度比其他两个快1.5倍。