PHP Javascript : Playing with multi-dimensional array

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