views:

103

answers:

5

Hi,

again me:

following array;

$myArray = array('FOO', 'BAR', 'HELLO');

i need:

$myArray['FOO']['BAR']['HELLO'] = 0;

any ideas?

+1  A: 

You might try $newArray[$myArray[0]][$myArray[1]][$myArray[2]] = 0;

Myles
+1  A: 
$newArray = array($oldArray[0] => array($oldArray[1] => array($oldArray[2] => 0)));
erenon
sure but i need to create it "automatic" i dont know how many keys or values in my source.. (-:
ArneRie
+1  A: 

you could do it with recursion:

function arrToKeys(&$arr,$initialCount){
   if($initialCount == 0 ){
      return $arr;
   }
   else{
      $newKey = $arr[0];
      unset($arr[0]);
      $arr[$newKey] = $arr;
      $initialCount--;
      return arrToKeys($arr,$initialCount);  
   }
}

//then call it like this
$newArr = arrToKeys($myArray,count($myArray));
GSto
That function throws a segmentation fault. And you're missing a closing bracket
Andrei Serdeliuc
added closing bracket.
GSto
+10  A: 
 function onion($a) {
  return $a ? array(array_shift($a) => onion($a)) : 0;
}

$myArray = array('FOO', 'BAR', 'HELLO');
print_r(onion($myArray));

//edit: actually doc's solution is better, his/her code, a bit improved

  $new = 0;
  foreach (array_reverse($myArray) as $v)
       $new = array($v => $new);
stereofrog
If I could vote twice, I would! Excellent implementation!
Andrei Serdeliuc
very nice, this is much cleaner than the implementation I wrote. ArneRie really sould accept this as being correct.
GSto
+1  A: 
$newarr[array_pop($myarr)] = 0;
foreach (array_reverse($myarr) as $v)
    $newarr[$v] = $newarr;
doc
Excellent! I improved this a bit, see edit to my post
stereofrog
Every recursive algorithm has non-recursive equivalent ;)
doc