Jump to content

Dynamicly create n-dimensional arrays?


Omirion

Recommended Posts

I'll try to explain as best i can.

 

I'm trying to write a function that creates n-dimensional arrays.

Why i need this is far to long to explain.

 

But imagine you have this.

function createArr($depth,$key,$val){
}

 

And you call it like so.

$a = createArr(3,0,'moo')

 

The result would be

 

$a[0][0][0] == 'moo'

 

Say you call it like this.

 

$a = createArr('7','15','foo');

 

You would get

 

$a[0][0][0][0][0][0][15] = 'foo'

 

 

 

Any ideas on how this effect can be achieved?

 

Basically i need to add as many []'s as i specify in the funcs depth argument.

Link to comment
Share on other sites

function createArr($depth,$key,$val){
$end = array($val); // so $end[0] = $val; 
$end = array_pad($end, $key*-1, 0); // adds $key number of 0s in front of the $val into the array making $end[$key] = $val;
for ($i = 0; $i < $depth - 1; $i++) {
  $end = array($end); // stacks the array into another array $depth - 1 times;
}
return $end;
}

Something like that?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.