0

I am having a problem appending a few options to an array of modules. I am using Opencart and trying to extend a module by adding an image. To do this and ensure that the code will not break anything in the future I wanted to add to the array instead of replace it.

This is the code I have so far:

if (isset($this->request->post['special_module'])) {
    $modules = $this->request->post['special_module'];
} elseif ($this->config->get('special_module')) { 
    $modules = $this->config->get('special_module');
}

$this->load->model('tool/image');

foreach ($modules as $module) {
    if (isset($module['image']) && file_exists(DIR_IMAGE . $module['image'])) {
        $image = $module['image'];
    } else {
        $image = 'no_image.jpg';
    }           

    array_push($module, array(
        'image'        => $image,
        'thumb'        => $this->model_tool_image->resize($image, 100, 100)
    )); 
} 
print_r($modules);exit;
$this->data['modules'] = $modules;

Print Array, no image or thumb:

Array
(
    [0] => Array
        (
            [image_width] => 307
            [image_height] => 234
            [layout_id] => 1
            [position] => column_right
            [status] => 1
            [sort_order] => 1
        )

)

When I do array_push do I need to assign this back to the array?

4

3 回答 3

2

$module 每次迭代时都会被 foreach() 循环覆盖。因此,您的推送基本上是一个空操作,因为 foreach 将破坏前一个 $module(您推送到的),而下一个 $module 值来自 $modules。你需要更多这样的东西:

foreach($modules as &$module) {
    ...
    $module['image'] = $image;
    $module['thumb'] = ...;
}

foreach 中的&before $module 将其转换为引用,因此$module对循环内的任何修改都将修改 $modules 中的原始元素,而不是在每次迭代时都会被丢弃的副本。

于 2011-11-24T15:11:21.113 回答
1

$module,在您的 foreach 循环中是内容的副本。您将需要通过引用访问它,或推回实际的数组 $modules。

尝试将 foreach 签名修改为以下内容:

foreach ($modules as &$module) {
于 2011-11-24T15:13:50.020 回答
0

尝试使用 array_merge 而不是 array_push

array_merge($module, array(
    'image'        => $image,
    'thumb'        => $this->model_tool_image->resize($image, 100, 100)
)); 

编辑:

另外,由于 print_r 输出正确的应该是array_merge($module[0], array(...));

于 2011-11-24T15:13:47.850 回答