Patrick
Patrick

Reputation: 7185

Use an array as an index to access a multidimensional array in PHP

I am having a problem accessing an object in a multidimensional array.

THE CONTEXT

Basically, I have an object (category) which consists of Name, ID, ParentID and more. I also have an array ultimateArray which is multidimentional.

For a given category, I am writing a function (getPath()) that will return an array of ids. For example, an object named Granny Smith has a parentID of 406 and is therefore a child of Food(5) -> Fruits(101) -> Apples(406). The function will return either an array or string of the ids of the objects parents. In the above example this would be: 5 -> 101 -> 406 or ["5"]["101"]["406"] or [5][101][406]. Food is a root category!

THE PROBLEM

What I need to do is use whatever is returned from getPath() to access the category id 406 (Apples) so that I can add the object Granny Smith to the children of Apples.

The function $path = $this->getPath('406'); is adaptable. I am just having difficulty using what is returned in the following line:

$this->ultimate[$path]['Children'][]= $category;

It works when I hard code in:

$this->ultimate["5"]["101"]["406"]['Children'][]= $category;
//or
$this->ultimate[5][101][406]['Children'][]= $category;

Any help is much appreciated.

Upvotes: 3

Views: 207

Answers (2)

Willy Pt
Willy Pt

Reputation: 1845

Suppose you have the array like below

<?php
$a = array(
        12 => array(
                65 => array(
                    90 => array(
                        'Children' => array()
                    )
                )
            )
    );

$param = array(12, 65, 90); // your function should return values like this
$x =& $a; //we referencing / aliasing variable a to x
foreach($param as $p){
    $x =& $x[$p]; //we step by step going into it
}
$x['Children'] = 'asdasdasdasdas';
print_r($a);

?>`

You can try referencing or aliasing it
http://www.php.net/manual/en/language.references.whatdo.php
The idea is to make a variable which is an alias of your array and going deep from the variable since we can't directly assigning multidimensional key from string (AFAIK)


output

Array
(
    [12] => Array
        (
            [65] => Array
                (
                    [90] => Array
                        (
                            [Children] => asdasdasdasdas
                        )

                )

        )

)

Upvotes: 2

nvanesch
nvanesch

Reputation: 2600

You can use a recursive function to access the members. This returns NULL if the keys do not correspond with the path, but you could also throw errors or exceptions there. Also please note that i have added "Children" to the path. I have done this so you can use this generically. I just did an edit to show you how to do it without children in the path.

<?php

$array = array(1 => array(2 => array(3 => array("Children" => array("this", "are", "my", "children")))));
$path = array(1, 2, 3, "Children");
$pathWithoutChildren = array(1, 2, 3);

function getMultiArrayValueByPath($array, $path) {
    $key = array_shift($path);
    if (array_key_exists($key, $array) == false) {
        // requested key does not exist, in this example, just return null
        return null;
    }
    if (count($path) > 0) {
        return getMultiArrayValueByPath($array[$key], $path);
    }
    else {
        return $array[$key];
    }
}

var_dump(getMultiArrayValueByPath($array, $path));
$results = getMultiArrayValueByPath($array, $pathWithoutChildren);
var_dump($results['Children']);

Upvotes: 0

Related Questions