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.

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.