1

I have a variable $temp which contains:

['test1']['test2']['test3']

I want to get the value of this variable in an array : $array.
I tried $array[$temp] and other possibilities.

getNavItemIndex returns an array containing the position of the value asked

Edit:

$input = array();
$input['level0']['level1']['somekey'] = "value of somekey";
$input['level0']['level1']['somekey2'] = "value of somekey2";
$input['level0']['level1b']['somekey1b'] = "value of somekey1b";
$input['level0']['level1']['level2']['somekey1c'] = "value of somekey1c";
$json1 = getNavItemIndex($input, "value of somekey1c");  
foreach ($json1 as $key => $value) {
    $temp .= "['";
    $temp .= $value; 
    $temp .= "']";   
}
echo $temp; // ['level0']['level1']['level2']['somekey1c']
echo $input[$temp]; //value of somekey1c
5
  • 1
    Can you post the code that you have so far ? Commented Jun 2, 2015 at 9:04
  • 1
    And also post the expected output Commented Jun 2, 2015 at 9:05
  • Should it look like $temp[0]='test1',$temp[1]='test2' & $temp[2]='test3' ? Commented Jun 2, 2015 at 9:05
  • 1
    I have edited, i want this expected output : value of somekey1c Commented Jun 2, 2015 at 9:11
  • I've updated my answer below according to your update. Commented Jun 2, 2015 at 9:25

1 Answer 1

0

Changed the answer after your edit.

$output = null;
for($i = 0; $i < count($temp); $i++) {
    if($output === null && isset($input[$temp[$i]])) {
        $output = $input[$temp[$i]];
    }elseif (isset($output[$temp[$i]])) {
        $output = $output[$temp[$i]];
    }else {
        $output = null;
    }
}
echo $output;

You also need to edit your code when you are creating the temp array.

$temp = [];
foreach ($json1 as $key => $value) {
    $temp[] = $value;   
}

Update A more eloquent and reusable solution.

function getByKeys($arr, $keys) {
    $key = array_shift($keys);
    if(isset($arr[$key])) {
        if(count($keys) > 0) {
            return getByKeys($arr[$key], $keys);
        }else {
            return $arr[$key];
        }
    }else {
        throw new Exception('Key is not isset');
    }
}

echo getByKeys($input, $temp);
Sign up to request clarification or add additional context in comments.

2 Comments

I was looking for more simple but it works thank you :)
I think the new solution would be a little more simple, aslo it's more reusable :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.