我在访问多维数组中的对象时遇到问题。
背景
基本上,我有一个对象(类别),它由Name
、ID
、ParentID
等组成。我还有一个多维数组 ultimateArray
。
对于给定的类别,我正在编写一个函数 (getPath()
),它将返回一个 ids
数组。例如,名为 Granny Smith
的对象的 parentID
为 406,因此是 Food(5) -> Fruits(101) -> Apples(406) 的子对象。该函数将返回对象父对象 ID 的数组或字符串。在上面的示例中,这将是:5 -> 101 -> 406
或 ["5"]["101"]["406"]
或 [ 5][101][406]
。食物是根类别!
问题
我需要做的是使用从 getPath()
返回的任何内容来访问类别 ID 406
(Apple),以便我可以添加对象 史密斯奶奶
送给Apples
的 children 。
函数 $path = $this->getPath('406');
是自适应的。我只是在使用以下行中返回的内容时遇到了困难:
$this->ultimate[$path]['Children'][]= $category;
它在我硬编码时有效:
$this->ultimate["5"]["101"]["406"]['Children'][]= $category;
//or
$this->ultimate[5][101][406]['Children'][]= $category;
非常感谢任何帮助。
最佳答案
假设你有如下数组
<?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
)
)
)
)
关于php - PHP中使用数组作为索引访问多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16361485/