• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Foreach loop in controller

#1
[eluser]rvillalon[/eluser]
How do I run a foreach loop to change the values of an array before I send it out to the view for displaying?

I pass an array to my viewer as follows:
$data['product_list'] = $this->products_model->get_products($data['user_id']);
$this->load->view('admin/products/index', $data);

Then I run a foreach loop.

However, I want to change the value of all the $data['product_list']['id'] before I send it off. How would I go about doing that?

I tried the following, but can't seem to get it to work:

foreach($data['product_list'] as $product) {
$product['id'] = 1;
}

#2
[eluser]Dam1an[/eluser]
The way you're trying ti isn't working because $product isn't actually the item in the array
You could try doing as &$product which should do it by reference (I've never tried this, but read it works)
or the way I do it is
Code:
foreach($data['product_list'] as $key=>$product) {
  $data['product_list'][$key]['id'] = // Do what you want here
}

(Also, just a personal preference, but I would do the manipulation and then add the processed array to $data, but that might just be me)

#3
[eluser]rvillalon[/eluser]
Thanks Dam1an. It worked.

This is what I eventually came up with, along with your preference:

Code:
$arr = $this->products_model->get_products($data['user_id']);

foreach($arr as $key=>$product) {
  $arr[$key]['id'] = (do something here);
}

$data['product_list'] = $arr;


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.