Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a value deeply in a multi-dimension array by a sequence of keys

Tags:

arrays

php

If an array $array

and keys sequence $keys = array('key1','key2','key3')

how to get $array[$keys[1]][$keys[2]][$keys[3]] given the number of keys is unsure, there could be 4 keys, or 1 key, etc.?

My code currently is:

switch(count($keys)) {
    case 1:
        if(array_isset($array[$keys[0]]), $array)
            $value = $array[$keys[0]];
        break;
    case 2:
        if(array_isset($array[$keys[0]][$keys[1]]), $array[$keys[0]])
            $value = $array[$keys[0]][$keys[1]];
        break;
    case 3:
        if(array_isset($array[$keys[0]][$keys[1]][$keys[2]]), $array[$keys[0]][$keys[1]])
            $value = $array[$keys[0]][$keys[1]][$keys[2]];
        break;
    case 4:
        if(array_isset($array[$keys[0]][$keys[1]][$keys[2]][$keys[3]]), $array[$keys[0]][$keys[1]][$keys[2]])
            $value = $array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];
        break;
    default:
        break;
}

function array_isset($key, Array $array) {
  if(isset($array[$key])) {
    return true;
  }
  return array_key_exists($key, $array);
}

Any better idea? I don't want to use eval


Updated, so the final code according to Alma Do Mundo

$result = $array[$keys[0]];
for($i=1;$i<count($keys);$i++) {
    if(array_isset($keys[$i], $result))
        $result = $result[$keys[$i]];
    else {
        $result = null;
        break;
    }
}
like image 772
Edward Avatar asked Oct 21 '22 00:10

Edward


1 Answers

With a simple loop:

//for PHP <=5.3 replace short [] to array()
$rgData   = ['key1'=>['key2'=>['key3'=>'test', 'key4'=>'data'], 'key5'=>'done']];
$rgKeys   = ['key1','key2','key3'];
$rgResult = $rgData[$rgKeys[0]];
for($i=1; $i<count($rgKeys); $i++)
{
   $rgResult=$rgResult[$rgKeys[$i]];
}

There could be an option with eval, but I'd say - never use eval - if you can avoid it.

like image 132
Alma Do Avatar answered Oct 31 '22 12:10

Alma Do