Skip to content

Instantly share code, notes, and snippets.

@branquito
Created August 21, 2012 14:44
Show Gist options
  • Save branquito/3416173 to your computer and use it in GitHub Desktop.
Save branquito/3416173 to your computer and use it in GitHub Desktop.
multiarray example PHP->JavaScript
<?php
$items = array(
'subject'=> array(
'easy' => array('music','history'),
'difficult' => array('maths','science')
),
'sports'=>array(
'easy' => array('cricket'),
'difficult' => array('football','basketball')
)
);
$keyName = array();
?>
<html>
<head>
<title>PHP/Javascript : Playing with multi-dimensional array</title>
<script type="text/javascript" language="javascript">
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;
}
}
?>
function populateList() {
var subjectEasy = document.getElementById('subject_easy');
var subjectDiff = document.getElementById('subject_difficult');
var sportsEasy = document.getElementById('sports_easy');
var sportsDiff = document.getElementById('sports_difficult');
for (i=0; i<itemData['subject']['easy'].length; i++)
{
subjectEasy.options[subjectEasy.options.length]=new Option(itemData['subject']['easy'][i],itemData['subject']['easy'][i])
}
for (i=0; i<itemData['subject']['difficult'].length; i++)
{
subjectDiff.options[subjectDiff.options.length]=new Option(itemData['subject']['difficult'][i],itemData['subject']['difficult'][i])
}
for (i=0; i<itemData['sports']['easy'].length; i++)
{
sportsEasy.options[sportsEasy.options.length]=new Option(itemData['sports']['easy'][i],itemData['sports']['easy'][i])
}
for (i=0; i<itemData['sports']['difficult'].length; i++)
{
sportsDiff.options[sportsDiff.options.length]=new Option(itemData['sports']['difficult'][i],itemData['sports']['difficult'][i])
}
}
</script>
</head>
<body>
<form action="">
<input type="button" name="populate" onclick="populateList()" value="Populate selection lists" />
<p></p>
<fieldset>
<legend>Subject</legend>
<fieldset>
<legend>Easy</legend>
<select name="subject_easy" id="subject_easy">
</select>
</fieldset>
<fieldset>
<legend>Difficult</legend>
<select name="subject_difficult" id="subject_difficult">
</select>
</fieldset>
</fieldset>
<p></p>
<fieldset>
<legend>Sports</legend>
<fieldset>
<legend>Easy</legend>
<select name="sports_easy" id="sports_easy">
</select>
</fieldset>
<fieldset>
<legend>Difficult</legend>
<select name="sports_difficult" id="sports_difficult">
</select>
</fieldset>
</fieldset>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment