1

again me:

following array;

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

i need:

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

any ideas?

5 Answers 5

14
 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);
Sign up to request clarification or add additional context in comments.

1 Comment

very nice, this is much cleaner than the implementation I wrote. ArneRie really sould accept this as being correct.
2
$newarr[array_pop($myarr)] = 0;
foreach (array_reverse($myarr) as $v)
    $newarr[$v] = $newarr;

1 Comment

Every recursive algorithm has non-recursive equivalent ;)
1

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

Comments

1
$newArray = array($oldArray[0] => array($oldArray[1] => array($oldArray[2] => 0)));

1 Comment

sure but i need to create it "automatic" i dont know how many keys or values in my source.. (-:
1

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));

1 Comment

That function throws a segmentation fault. And you're missing a closing bracket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.