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
https://forums.phpfreaks.com/topic/215248-dynamicly-create-n-dimensional-arrays/
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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.