0

Please see my code bellow, I want to get $arr['jimmy']['age'] here. The string is jimmy.age which will be posted from ajax

<?php
$arr=array(
    'jimmy'=>array(
        'age'=>31
    )
);

$str='jimmy.age';
$keys_tree=explode('.',$str);
$x='';
foreach($keys_tree as $k=>$v){
    $x.='["'.$v.'"]';
}
echo $arr$x; //error here; how can i get $arr['jimmy']['age'] using $arr joining str ['jimmy']['age']
5
  • explain what you think $arr$x means, please. If, while you try to do so, you realise what you did wrong, there is no shame in removing this question. Commented Nov 28, 2013 at 3:35
  • You can't do it like you are trying, $x contains a string which looks like array notation. Commented Nov 28, 2013 at 3:39
  • try this : echo $arr.$x; Commented Nov 28, 2013 at 3:42
  • @Rohit, it won't work like you said to try $arr.$x. Commented Nov 28, 2013 at 3:44
  • It would with eval(), but there's too much drama attached to that function Commented Nov 28, 2013 at 3:53

1 Answer 1

2

One way is to walk the array and keep track of each level with references:

$str ='jimmy.age';
$keys_tree = explode('.', $str);

$pointer = $arr;

while($key = array_shift($keys_tree)){

  if(!isset($pointer[$key]))
    throw new Exception(sprintf("Key %s doesn't exist", $key));

  $pointer = &$pointer[$key];      
}

echo $pointer;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.