S
S
Sasha Brahms2015-11-08 17:40:46
PHP
Sasha Brahms, 2015-11-08 17:40:46

How to access a multidimensional array given a string?

there is an array
array('one' => array('two'=>'kek'));
and a string
$string = '[one][two]';
how to access an array by string?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Latyshev, 2015-11-08
@magalex

$a = array('one' => array('two'=>'kek'));
$string = '[one][two]';
preg_match_all('/(\+\])/',$string,$matches);
$a[$mathes[0][0]][$mathes[0][1]];

A
Anton B, 2015-11-08
@bigton

Universal solution for a large number of keys

$arr = ['one' => ['two' => 'kek']];
$key = '[one][two]';

function arr_key_val($arr, $key) {

  $keys = trim($key, '[]');
  $keys = explode('][', $keys);

  $return = $arr;
  foreach ($keys as $k)
    $return = $return[$k];

  return $return;
}

echo arr_key_val($arr, $key);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question