Home » Javascript, PHP

PHP Javascript : Playing with multi-dimensional array

23 October 2009 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

email

Related posts:

  1. PHP: Parse Unparse String Array
  2. print_r in Javascript
  3. Go back link in Javascript
  4. jQuery: Print array and object
  5. Displaying date and time
  6. Javascript: Add Remove HTML elements
  7. Javascript: Show/Hide HTML elements
  8. Magento: How to search or filter by multiselect attribute in admin grid?
  9. Multiple file upload with jQuery and php
  10. Javascript: How to Submit form and Change form action?

php magento mukesh chapagain

Get New Post by Email
RSS Feed Subscribe RSS Feed