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
https://forums.phpfreaks.com/topic/235860-multidimensional-arrays-foreachloop/
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 />";
	}
}

}

  • 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>";

?>

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.