不知道字符串键的多维关联数组

时间:2018-02-16 18:47:25

标签: php arrays multidimensional-array associative-array

我需要能够获取未知深度的数组并从特定维度获取密钥而不知道它们的值。例如:

$deepArray = array(
    "fooArray1_1" => array(
        "fooArray2_1" => array(
           "fooA" => "3",
           "fooB" => "foo string example 1",
            ),
        "fooArray2_2" => array(
           "fooA" => "foo number 10",
           "fooB" => "foo string example",
            ),
    ),
    "fooArray1_2" => array(
        "fooA" => "foo number 102",
        "fooB" => "foo string example 3",
    ),
);

我希望能够从$deepArray[0][1]获取密钥,此实例中的密钥应为fooArray2_2

2 个答案:

答案 0 :(得分:0)

function getKey($arr, $path) {
    // save last step
    $s = array_pop($path);
    // go through the array to the desired point 
    foreach($path as $x) {
        $arr = $arr[array_keys($arr)[$x]];
    }
    // get target key  
    return array_keys($arr)[$s]; 
}

echo getKey($deepArray, [0,1]); // fooArray2_2

demo

答案 1 :(得分:0)

你说你想要密钥,但是如果你真的想要那个密钥下的数据;这是我的回答How to write getter/setter to access multi-level array by key names?中的一个示例,修改后使用www.xyz.com/wp-content/uploads/2015/03/ASSEMBLY2.jpg进行数字索引:

array_values

function get_by_offsets($path, $array) { $temp = &$array; foreach($path as $key) { $temp = array_values($temp); $temp =& $temp[$key]; } return $temp; } $result = get_by_offsets([0, 1], $deepArray); //returns NULL if the path doesn't exist 下生成数据:

$deepArray['fooArray1_1']['fooArray2_2']