Below is my array, where I want to replace [image] => 201310171708033183470.jpg with full path like:

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

I want to give a full path to all the image name below:

[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
                    )

            )

Which is the quickest and most optimized way of doing that?

有帮助吗?

解决方案

You must use a & with foreach to use the variable itself and not a copy of the variable.

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

An other way is to use array_map:

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

Or array_walk:

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

For your test array, the first way seems to be faster. With a huge array (70000 items) you obtain foreach<array_walk<array_map with foreach ~ 1.5x faster than the two others.

其他提示

Hope it may helps,

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

        $image['image'] = 'http://localhost/website/uploads/'.$image['image'];
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top