Answer the question
In order to leave comments, you need to log in
How to "walk" through the keys of an array?
Hello.
Straight to the point - an example.
We have an array like this:
$array = array(
'one' => 'hi',
'two' => 'privet',
'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);
$str = 'three|three_1';
$exp = explode('|', $str);
$key = '["'.implode('"]["', $exp).'"]'; //["three"]["three_1"]
var_dump($array[$key]); //null
Answer the question
In order to leave comments, you need to log in
for this narrow example something like this:
$array = array(
'one' => 'hi',
'two' => 'privet',
'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);
$str = 'three|three_1';
$keys = explode("|", $str);
var_dump($array[$keys[0]][$keys[1]]);
<?php
function foo($array, $str){
$keys = explode('|', $str);
$keysCount = count($keys);
$result = $array;
for($i = 0; $i < $keysCount; $i++){
if(!is_array($result) && $i < ($keysCount - 1)){
throw new Exception("Array depth not expected");
}
if(!isset($result[$keys[$i]])){
throw new Exception(sprintf("Key '%s' not found", $keys[$i]));
}
$result = $result[$keys[$i]];
}
return $result;
}
$array = array(
'one' => 'hi',
'two' => 'privet',
'three' => array('three_1' => 'hi', 'three_2' => 'privet'),
);
$str = 'three|three_1';
var_dump(foo($array, $str));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question