2

To set a value in a multidimentional array is easy. E.g.:

$myArray['levelA']['levelB']['levelC'] = $value

to read it is simple, too. E.g.:

$value = $myArray['levelA']['levelB']['levelC']-

Easy when i know how many levels are used. But what is when we do not know how many levels could occure?

What if i have a config file like this:

levelA.levelB.levelC.levelD = someValue

and what if i want to use levelA.levelB.levelC.levelD to map it (as a "path") to the multidimentional array, whichout knowing how deep my config could be?

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
DanielaWaranie
  • 1,405
  • 1
  • 17
  • 22
  • You could loop down level by level. First iteration, `$foo = $myArray['a']` then `$foo = $foo['b']` then `$foo = $foo['c']`, resulting in `$foo == $myArray['a']['b']['c'] //true` – Kavi Siegel Jan 09 '13 at 23:59
  • I don't think I am following what you are asking. I am not sure what you config file is doing as that looks like a concatenation of constants that you are trying to assign another constant to. Maybe show a more real-world example of what you are trying to do. – Mike Brant Jan 10 '13 at 00:00

2 Answers2

1

Here's a small class I wrote that would determine the number of dimensions. You could easily modify it to do whatever you wanted, or just use the number it returns to guide your own function:

class DimensionCounter {

    var $i;

    public function count($array) {
        $this->i = 1;
        return $this->readArray($array);
    }

    private function readArray($array) {

        foreach($array as $value) {
            if (is_array($value)) {
                $this->i++;
                $this->readArray($value);               
            }
            return $this->i;
        }
    }
}

In your case, $counter = new DimensionCounter(); $num = $counter->count($value); would give you the number of dimensions.

ChrisMoll
  • 365
  • 1
  • 12
-1

But what is when we do not know how many levels could occure[sic!] ?

Well it's just that you don't know how many levels there are or not.

You can use isset() to find out easily anyway:

$exists = isset($myArray['levelA']['levelB']['levelC']['levelD']);

But I must also admit that I have some problem to understand you question.

Are you looking for:

or similar?

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • To access the value like you did you need to know the depth of the array on coding time. That is not the way to handle it dynamically on runtime. – DanielaWaranie Feb 11 '13 at 00:41
  • @DanielaWaranie: Hence the `isset` to check if. You can apply it to any depth. In the answer no value at all is accessed. Take care. – hakre Feb 11 '13 at 09:24