【问题标题】:Use an array as an index to access a multidimensional array in PHPPHP中使用数组作为索引访问多维数组
【发布时间】:2013-05-03 23:57:11
【问题描述】:

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

背景

基本上,我有一个由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(Apples),以便我可以将对象 Granny Smith 添加到 Apples 的子代。

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

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

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

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

非常感谢任何帮助。

【问题讨论】:

  • getPath() 返回什么?
  • getPath() 可以返回任何内容。目前我返回一个数组["5"]["101"]["406"],但可以轻松更改代码以返回一串索引或其他任何内容。
  • ["5"]["101"]["406"] 根本不是一个数组!那么,您是否要返回该数组切片中的元素?还是包含您所写内容的字符串?什么 ? :)
  • 如果您在创建 $ultimate 的位置发布代码可能会有所帮助,这样我们就可以看到您的数组的结构以及不同级别之间的关系。它是一个关联数组,例如“food” => 5, “fruits” => 101, “apples” => 406,还是一个分层数组数组,例如“food” => array ("fruits" 、“蔬菜”等)
  • getPath() 函数不是我遇到的问题 - 它只是创建一个数组或索引列表来访问相关类别。我正在苦苦挣扎的是如何使用这些索引来访问Granny Smith 的父类别。请查看更新的问题,详细说明硬编码时的工作原理。

标签: php multidimensional-array


【解决方案1】:

假设你有如下的数组

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

                )

        )

)

【讨论】:

  • 它需要一点点适应,但我认为你的代码工作得很好(现在我对引用的理解更好了)!非常感谢!我会评论我的更改,并在一切都整理好并且我有一个可行的解决方案时标记为正确。
【解决方案2】:

您可以使用递归函数来访问成员。如果键与路径不对应,这将返回 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']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2021-08-19
    • 2021-12-25
    • 2014-03-08
    相关资源
    最近更新 更多