php - PHP中使用数组作为索引访问多维数组

标签 php multidimensional-array

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

背景

基本上,我有一个对象(类别),它由NameIDParentID 等组成。我还有一个多维数组 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/

相关文章:

javascript - 将 Gmail 放入 Google 表格中

php - 在特定时间向所有用户发布信息的 Facebook 应用程序 (php)

c# - 二维数组未按预期在 C# 中创建

python - Python 中 numpy 数组和多维列表的区别?

javascript - 在复选框勾选上隐藏表行内容

c - 在 C 中使用 strcmp 和 bubblesort 对二维数组进行排序

java - 我读取了文本文件,现在如何将值存储到二维数组中?

php - 不能将 PDOStatement 类型的对象用作数组

php - 缺少 [Route : utente. show] [URI: registrazione/{utente}] 所需的参数

php - 在自定义用户模块中扩展 ZfcUser 的 UserController