Jump to content

Multidimensional Arrays & foreach....loop?


chris57828

Recommended Posts

Hi everyone,

 

If you take a look at my code below I am having trouble echoing the key/ value pair of the 'sex' array which is a sub array of 'pens'.  I have tried so many different ways but to no avail, thanks Chris!

 

<?php
$products = array(
'paper' => array(
	'copier' => "Copier & Multipurpose",
	'inkjet' => "Inkjet Printer",
	'laser'  => "Laser Printer",
	'photo'  => "Photographic Paper"),

'pens' => array(
	'ball'   => "Ball Point",
	'hilite' => "Highlighters",
	'marker' => "Markers",
	'sex' => array (
			'condom' => "Protection")),

'misc' => array(
	'tape'   => "Sticky Tape",
	'glue'   => "Adhesives",
	'clips'  => "Paperclips") );

echo "<pre>";
foreach ($products as $section => $items )

foreach ($items as $key => $value)
	echo "$section:\t$key\t($value)<br>";

echo "</pre>";
?>

:'(

Link to comment
Share on other sites

You'll need to use a third foreach loop to echo the key/value pairs for the  $products['pens']['sex'] array

 

foreach ($products as $section => $items)
{
foreach ($items as $key => $value)
{
	echo "$section:\t$key\t($value)<br>";

	// check whether the current item is an array!
	if(is_array($value))
	{
		echo "$key is sub array:<br />";
		foreach($value as $subKey => $subValue)
			echo "$subKey:\t$subValue<br />";
	}
}

}

Link to comment
Share on other sites

  • 1 year later...

Hi ,

 

Could you please help me to sort the array of array['laser'] to top. Thank in advance.

 

<?php

$products = array(

'paper' => array(

'copier' => "Copier & Multipurpose",

'inkjet' => "Inkjet Printer",

'laser' => "Laser Printer",

'photo' => "Photographic Paper"),

 

'pens' => array(

'copier' => "Ball Point",

'inkjet' => "Highlighters",

'laser' => "Markers",

'photo' => "Protection")),

 

'misc' => array(

'copier' => "Sticky Tape",

'inkjet' => "Adhesives",

'laser' => "Sweet",

'photo' => "Protection"));

 

echo "<pre>";

foreach ($products as $section => $items )

 

foreach ($items as $key => $value)

echo "$section:\t$key\t($value)<br>";

 

echo "</pre>";

?>

Edited by sraj
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.