Boopathi N
Boopathi N

Reputation: 406

php using more then one array in foreach

in controller i send the object to view like:

public function comapre_array()
{

 $data['pro1']="result from model";   //product details

 $data['pro2']="result from model";   //product details

 $data['pro3']="result from model";   //product details

  $this->load->view('user/product_comp',$data);
}

and in my view i need to display that in table to comparison,

i need to take the three array value in single loop using foreach,is it is possible,

i tried like this

foreach($pro1 as $m,$pro2 as $n,$pro3 as $o){
    //printing values
}

but it shows error,

please suggest me is there is any other ideas to implement this,

Upvotes: 1

Views: 56

Answers (2)

Alex
Alex

Reputation: 478

If your different arrays have the same key structure you could do something like that :

foreach($pro1 as $key => $pro){


    if(isset($pro2[$key],$pro3[$key])) {
        //print your values here
    } else {
        //Your arrays don't have the same key structure
    }

}

Upvotes: 0

masterFly
masterFly

Reputation: 1112

Make your data set as,

$data['product']['pro1']="result from model";   //product details
$data['product']['pro2']="result from model";   //product details
$data['product']['pro3']="result from model";   //product details

Basically put your products under a new array key called product.

And in your view, get the $product first and loop it.

foreach( $product as $prod_key => $prod_value ){
    // $prod_key = pro1, pro2, pro3
    // $prod_value = product details
}

Hope this helps!

Upvotes: 1

Related Questions