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?
$module is being overwritten by the foreach() loop every time it iterates. So your push is basically a null-op, becaus foreach will destroy the previous $module (that you pushed to) with the next $module value coming out of $modules. You’d need something more like this:
The
&before $module in the foreach turns it into a reference, so any modifications to$modulewithin the loop will modify the original element in $modules, rather than a copy which would get trashed on every iteration.