Home » Javascript, PHP

PHP Javascript : Playing with multi-dimensional array

23 October 2009 337 views No Comment Popularity: 4% Share/Bookmark

I had to work on multi-dimensional array with javascript and php. I had a multi-dimensional array in php. I had to load it into javascript array and then populate the html selection list.

The challenge for me was to create multi-dimensional array in javascript and populate selection list with for loop in javascript.

Here is the full code containing php array, creating javascript array, using for loop in javascript to populate selection list in onclick event.

Given php array:-


<?php
$items = array(
'subject'=> array(
'easy' => array('music','history'),
'difficult' => array('maths','science')
),
'sports'=>array(
'easy' => array('cricket'),
'difficult' => array('football','basketball')
)
);

$keyName = array();
?>

Creating array in javascript with php array:-


var itemData = new Array();
	<?php
	foreach($items as $key=>$value)
	{
		foreach($value as $k=>$v)
		{
			$v = implode(",",$v);

			if(!in_array($key,$keyName))
			{
				?>
				itemData['<?php echo $key; ?>'] = new Array();
				<?php
			}
			?>
				itemData['<?php echo $key; ?>']['<?php echo $k; ?>'] = new Array('<?php echo str_replace(",","','",trim($v)); ?>');
		<?php
			$keyName[] = $key;
		}
	}
	?>

Populating selection list with javascript for loop:-

for (i=0; i<itemData['subject']['easy'].length; i++)
{
	subjectEasy.options[subjectEasy.options.length]=new Option(itemData['subject']['easy'][i],itemData['subject']['easy'][i])
}

Download Full Source Code

From Mukesh Chapagain's Blog | Post PHP Javascript : Playing with multi-dimensional array

Related posts:

  1. jQuery: Print array and object
  2. print_r in Javascript
  3. Javascript: Show/Hide HTML elements
  4. PHP: Parse Unparse String Array
  5. Javascript: Add Remove HTML elements

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.