Forum Moderators: coopster

Message Too Old, No Replies

PHP Dynamic Data Structure

I'm embarrased to ask....

         

Dabrowski

3:30 pm on Oct 8, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ok, this is really easy in Perl. But I'm learning PHP and can't for the life of me work out how to create a dynamic data structure.

I think my problem is with scope, but scoping in PHP seems a little vague to me at the moment.

Basically, I'm trying to generate a 3D array, e.g.:

Cars ->
...Model ->
......Colour ->

So one example of this might be

Ford
...Fiesta
......Black
......Blue
......Red
...Mondeo
......Green
......White
......Maroon
...Galaxy
......Silver
......Navy
......Dark Black

Vauxhall
...etc etc etc

Fiat
...etc etc etc

But none of the names are fixed. I'm trying to be nice an OO and create this in a class so it can be packaged and used anywhere.

I can't seem to get it to define an array and keep it defined! So far I have an include that looks like this:


class MyClass {
. . function __construct() {
. . . static $MyData;
. . }

. . function Create( $name) {
. . . if( !Isset( $MyData[ $name])) {
. . . . echo "$name - It's not defined<br>\n";
. . . . $MyData[ $name] = array();
. . . } else {
. . . . echo "$name - It is defined!<br>\n";
. . . }
. . }

}

$tree = new MyClass();

So, I'm running the Create function twice in the same script, with the same $name. The first time round it should say it's not defined and create it. The second it should say it is defined. But it's saying not defined all the time.

I've tried setting a value in the array to test on but still nothing. If I set values and immediately check them they are there. I think the array is being deleted at the end of the function.

TheMadScientist

5:21 pm on Oct 8, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Have you tried:
return $MyData;

Within your function(s)?

function Create( $name) {
. . . if( !Isset( $MyData[ $name])) {
. . . . echo "$name - It's not defined<br>\n";
. . . . $MyData[ $name] = array();
. . . } else {
. . . . echo "$name - It is defined!<br>\n";
. . . }
. . return $MyData;
. . }

Dabrowski

5:46 pm on Oct 8, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



No, I don't want to do it that way.

I'm actually making a multi-page form handler. I want to define all the form elements, on each page, in each set. I need the structure to remain global cos it's possible one set will branch to another, then return later.

So I want to call a function to create, or reset a set. Then add pages. Then add elements. These will then be stored in the session to survive page changes.

...unless of course, there's a better way?

Dabrowski

12:25 am on Oct 14, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I fixed it, it was a problem with scope.