0

I need to be able to take an array of unknown depth and get the keys from a specific dimension without knowing their values. For instance:

$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",
    ),
);

I would like to be able to get the key from $deepArray[0][1] where in this instance should be fooArray2_2.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
kglearning
  • 161
  • 1
  • 1
  • 7

2 Answers2

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

splash58
  • 26,043
  • 3
  • 22
  • 34
0

You say you want the key, but if you really want the data under that key; here's an example from my answer How to write getter/setter to access multi-level array by key names?, modified to use array_values to index numerically:

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

Yields the data under $deepArray['fooArray1_1']['fooArray2_2']:

Array
(
    [fooA] => foo number 10
    [fooB] => foo string example
)
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87