Jump to content

foreach and array question


xander85

Recommended Posts

I have a foreach loop that I am using now:

 

foreach($_SESSION['box'] as $CartItem[]=>$items)
{
echo "<p>";
	foreach($items as $item)
	{
		echo "<div class='order'>$item</div>";
	}
echo "</p>";
}
}

 

It works perfect and accomplishes what I need, partially. My question is this:

each $items will have 8 different rows and want to display each one different using css.

For example, i want to display three different rows like this:

 

for array value 1 i want: echo "<div class='order'>$item</div>"

array value 2 i want: echo "div class='order2'>$item</div>"

.....

all the way through that array.

 

How is this possible? I tried using if statements and I couldn't figure it out.

 

Also, how do you remove an arbitrary value from an array? Like my array contains five individuals array and I want to remove the third one.

Link to comment
https://forums.phpfreaks.com/topic/69129-foreach-and-array-question/
Share on other sites

I'm not sure that will work. Is there a way I can just create a "rule" for each value in each array since they are all going to have the same type of information.

 

My main array is setup as an array of the following array:

 

$items[] = (value1, value2, value3, value4, ...., value 8)

 

I want to assign a "rule" for each specific value (1 thru 8). Is there a way to do this like:

if($items[0])

{

....

}

if($items[1])

{

....

}

 

etc for all of each eight cases.

 

The main array will just feature X amount of the $items array and all need to be handled the same. Hope this helps.

To remove one value from the array use unset().

To assign an action to each "case", ie each value, use a switch statement

<?php
unset($items[3]);
foreach($items AS $k=>$i){
   switch($k){
      case 1:
        //do this
      case 2: 
       //do this
     default:
      //do this.
   }
}

?>

try

foreach($_SESSION['box'] as $CartItem[]=>$items)
{
echo "<p>";
	foreach($items as $key => $item)
	{
                        if($key) $class = 'order'.++$key; else $class = 'order';
		echo "<div class='$class'>$item</div>";
	}
echo "</p>";
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.