简体   繁体   English

使用数组作为索引来访问PHP中的多维数组

[英]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. 基本上,我有一个对象(类别),由NameIDParentID等组成。 I also have an array ultimateArray which is multidimentional. 我还有一个数组ultimateArray ,它是多维的。

For a given category, I am writing a function ( getPath() ) that will return an array of ids . 对于给定的类别,我正在编写一个函数( getPath() ),它将返回一个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). 例如,名为Granny Smith的对象具有406的parentID ,因此是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] . 在上面的例子中,这将是: 5 -> 101 -> 406["5"]["101"]["406"][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 . 我需要做的是使用从getPath()返回的任何内容来访问类别ID 406 (苹果),以便我可以将对象Granny Smith添加到Apples的子项中。

The function $path = $this->getPath('406'); 函数$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. 任何帮助深表感谢。

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 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) 我们的想法是创建一个变量,它是数组的别名并从变量深入,因为我们无法直接从字符串(AFAIK)分配多维键


output 产量

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

                )

        )

)

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. 如果键与路径不对应,则返回NULL,但您也可以在其中抛出错误或异常。 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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM