Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!

javascriptPHP

Creating a javascript array with one to many type relationship

Sometimes I need to build an array of lists with a one to many type relationship.

For example this data:
1. item1 has a parent of key1.
2. item2 has a parent of key2.
3. item3 has a parent of key1.

Using PHP after packing the array I will end up with something like this:

<?php

$m = array();

$m['key1'][] = 'item1';
$m['key2'][] = 'item2';
$m['key1'][] = 'item3';

print_r($m);

?>

Result:

Array
(
    [key1] => Array
        (
            [0] => item1
            [1] => item3
        )

    [key2] => Array
        (
            [0] => item2
        )

)

In javascript there is some options to do something similar. I ended up with something like this:
packedArr['key1'] = "item1,item3"
packedArr['key2'] = "item2"

Not exactly array in array[key] but the comma separated list did what I needed.

Here is the javascript itself. To test it you can use online javascript testers or just make up a html page with a button and maybe have onclick display document.getElementById("demo").innerHTML = output;

<script>
function packArr() {
var pA = Array();

var inA = [ 
  ["child1","parent1"],
  ["child2","parent2"],
  ["child3","parent1"],
  ["child4","parent1"],
  ["child5","parent2"]
  ];

var inALen = inA.length;
for (var i = 0; i < inALen; i++) {
    //alert(inA[i]);
  if (pA[inA[i][1]] == null) {
     pA[inA[i][1]] = inA[i][0];
  } else {
    pA[inA[i][1]] = pA[inA[i][1]] + "," + inA[i][0];
  }
}

res="";
for ( var key in pA ) { 
  res = res + key + ": " + pA[key] + "<br>";
};
//res = myArray["parent1"]; 
document.getElementById("demo").innerHTML = res;
}
</script>

admin

Bio Info for Riaan