Jump to content

How to setup & loop through multi-demensional array


n1concepts

Recommended Posts

I need a way to where I capture form content - product information via $_POST and insert that info into sessions so I can later display that info back via the 1st array's key.

 

Example: If the following products and that product's info is as follow:

 

Product1 -

feature xxx -

9.99

Product2 -

feature yyy -

13.41

Product3 -

feature zzz -

13.84

 

 

Q: how can I setup a multi-array to where I assign the attributes inside the 1st array then loop through the first array, which would be $_SESSION['product'][0], $_SESSION['product'][1], etc... then parse and display each assigned value (feature & price) for that specified product?

 

I'm not clearly on defining the multi-demensional array and then looping through the 1st array - getting to the 2nd to display the attributes before incrementing to the next key in the array 1st.

 

Can someone provided an example?

I need this to manage the order of information inserted in a form to print labels for shipments.

 

Here's a pretty full-featured example. If you get lost, check the manual. If that doesn't help, feel free to ask :D

 

<?php

$_SESSION['products'] = array(
'ABC0123' => array(
	'name' => 'MegaProduct XLT',
	'features' => array('waterproof','dustproof','rugged'),
	'price' => 99.99
),
'ABC0126' => array(
	'name' => 'MegaProduct XL',
	'features' => array('dustproof','rugged'),
	'price' => 79.99
),
'ABC0130' => array(
	'name' => 'MegaProduct',
	'features' => 'dustproof',
	'price' => 99.99
)
);

foreach( $_SESSION['products'] as $id => $data ) {
echo "<h3>{$data['name']} ($id)</h3>";
echo "Features: <ul>";
if( is_array($data['features']) )
	echo "<li>".implode("</li><li>", $data['features'])."</li>";
else
	echo "<li>{$data['features']}</li>";
echo "</ul>Price: \${$data['price']}";
}

?>

 

My solution is much 'cleaner' than the one on the cheat sheet, IMO

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.