3

我在访问多维数组中的对象时遇到问题。

上下文

基本上,我有一个由 、NameID组成的对象(类别) ParentID。我还有一个ultimateArray多维数组。

对于给定的类别,我正在编写一个函数 ( getPath()),它将返回一个ids. 例如,一个名为Granny Smitha的对象为parentID406,因此它是 Food(5) -> Fruits(101) -> Apples(406) 的子对象。该函数将返回对象父对象的 id 的数组或字符串。在上面的示例中,这将是:5 -> 101 -> 406or ["5"]["101"]["406"]or [5][101][406]。食物是一个根类别!

问题

我需要做的是使用返回的任何内容getPath()来访问类别 ID 406(Apples),以便我可以将对象添加Granny SmithApples.

功能$path = $this->getPath('406');适应性强。我只是在使用以下行中返回的内容时遇到了困难:

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

当我硬编码时它可以工作:

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

任何帮助深表感谢。

4

2 回答 2

2

假设您有如下数组

<?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);

?>`

您可以尝试引用或别名它
http://www.php.net/manual/en/language.references.whatdo.php
这个想法是创建一个变量,它是您的数组的别名并从变量中深入,因为我们不能直接从字符串分配多维键(AFAIK)


输出

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

                )

        )

)
于 2013-05-03T14:56:44.107 回答
0

您可以使用递归函数来访问成员。如果键与路径不对应,这将返回 NULL,但您也可以在那里抛出错误或异常。另请注意,我已将“儿童”添加到路径中。我已经这样做了,所以你可以通用地使用它。我刚刚做了一个编辑,向您展示如何在没有孩子的情况下做到这一点。

<?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']);
于 2013-05-03T14:50:30.157 回答