可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
How to send an indexes name for php array vairable.
the array is
$array = array('Somthing'=>array('More'=>array('id'=> 34)));
and now I want to display this thing but with a variable name I don't know how to explain so I write what I want to have.
$index_name = '[Something][More][id]'; $array{$index_name};
Is it possible in any way ?
回答1:
Not in one go like that. Here's how you'd do it:
$array['Something']['More']['id']
If you particularly wanted access multidimensional arrays with a single string, then you could build a function to do that:
function array_multi(Array $arr, $path) { $parts = explode(".", $path); $curr =& $arr; for ($i = 0, $l = count($parts); $i < $l; ++$i) { if (!isset($curr[$parts[$i]])) { // path doesn't exist return null; } else if (($i < $l - 1) && !is_array($curr[$parts[$i]]) { // path doesn't exist return null; } $curr =& $curr[$parts[$i]]; } return $curr; } // usage: echo array_multi($array, "Something.More.id"); // 34 echo array_multi($array, "Something.More"); // array("id" => 34)
回答2:
Recursive version supporting your syntax with square brackets:
$array = array('Something'=>array('More'=>array('id'=> 34))); $string = '[Something][More][id]'; echo scan_array($string, $array); function scan_array($string, $array) { list($key, $rest) = preg_split('/[[\]]/', $string, 2, PREG_SPLIT_NO_EMPTY); if ( $key && $rest ) { return scan_array($rest, $array[$key]); } elseif ( $key ) { return $array[$key]; } else { return FALSE; } }
回答3:
Ok, I know this is how people get shot. But c'mon, eval()
is not always the wrong answer.
$array = array('Something'=>array('More'=>array('id'=> 34))); $index_name = '[Something][More][id]'; eval('$val = $array'.$index_name.';'); // Wrap in a function or something
回答4:
You could do this with eval():
<?php $array = array('Somthing'=>array('More'=>array('id'=> 34))); $index_name = "['Somthing']['More']['id']"; $stmt='echo $array'.$index_name.';'; eval($stmt); ?>
UPDATE:
It seems some SO users are uncomfortable with the idea of using eval(). I think it makes sense to read this thread which discusses the pros and cons before deciding whether to use this in your own code.
回答5:
If you've cornered yourself into needing to do something like this, there's a pretty good chance you've done something else in a poor way. There's valid reasons to do this, but not very often.
function key_path($arr, $keys) { return $keys ? key_path($arr[array_shift($keys)], $keys) : $arr; } $arr['Something']['More']['id'] = 34; $keys = array('Something', 'More', 'id'); var_dump( key_path($arr, $keys));