Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 0.87 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. dynamically construct array
  2. function helper(&$array, $path, $value) {
  3.   $parent =& $array;
  4.   foreach ($path as $entry) {
  5.     if (!isset($parent[$entry])) {
  6.       $parent[$entry] = array();
  7.     }
  8.  
  9.     $parent =& $parent[$entry];
  10.   }
  11.  
  12.   $parent = $value;
  13.   // make this $parent[] if more than
  14.   // one $value will be added to the same path
  15. }
  16.  
  17. $array_go = array(); // or use some other array you already have
  18. helper($array_go, array(12, 20, 18), 1);
  19. helper($array_go, array(12, 15, 20), 2);
  20. helper($array_go, array(12, 10, 22), 3);
  21.  
  22. print_r($array_go);
  23.  
  24.  
  25. /*
  26. Array
  27. (
  28.     [12] => Array
  29.         (
  30.             [20] => Array
  31.                 (
  32.                     [18] => 1
  33.                 )
  34.  
  35.             [15] => Array
  36.                 (
  37.                     [20] => 2
  38.                 )
  39.  
  40.             [10] => Array
  41.                 (
  42.                     [22] => 3
  43.                 )
  44.  
  45.         )
  46.  
  47. )
  48. */