PHP动态数组索引名称 [英] PHP dynamic array index name
问题描述
我想传递一个函数数组的索引值 - 例如['client_name'] - 第一级值有效,因为我可以做到
I want to pass a function the index value of an array – e.g [‘client_name’] – a first level value works because I can do
$index = client_name;
function arraything ($index) { return $this->arraytolookat[$index]; }
问题是......如果它是一个多嵌套数组,我该怎么做?
The question is… how do I do this, if it’s a multi nested array?
我尝试了eval语句,显然它没有很好地评估括号......所以我尝试了这个。
I tried the eval statement and apparently it doesn’t evaluate brackets well … So I tried this.
$index = "[0][‘client_name’]";
Eval("$this->arraytolookat$index");
但它只是失败了......关于意想不到的结局[ - 任何想法?
But it just fails… winges about a unexpected [ - any Ideas?
编辑:我不知道这个函数可能需要多少级别,因此我不能在最后附加一定数量的括号。它不像它看起来那么简单^^
I do not know how many levels this function may be required to go into, therefore I cannot just append a set amount of brackets at the end. Its not as simple as it looks ^^
编辑2:基本上 - 我已经编写了一个表单验证工具,其中一个函数返回正确的帖子数据 - 我想要一个简单的当你输入表单元素的名称时 - 它会将POST数据返回到元素,例如getFormData(client_name) - 但是当表单变得更复杂时,它可以进入数组,我需要准备getFormData(['$ i'] client_name)的可能性或沿着这些行的东西,东西发生在该类的postdata中,因此必须使用该函数。我只是希望该函数采用字符串而不是数组。
EDIT 2: Basically - I have written a form validation tool and one of the functions returns correct post data - I wanted a simple method that when you enter the name of the form element - it would literally return teh POST data back to the element e.g getFormData("client_name") - however when a form gets more complex, it can go into arrays, I need to prepare for the possibility of getFormData("['$i']client_name") or somthing along those lines, stuff happens to the postdata in that class so that function must be used. I just want that function to take in a string not an array.
推荐答案
您可以将索引数组传递给下面的函数。所以,如果您想获得 $ some_array [0] ['client_name'] ['third_level_index']
,那么您可以这样做:
You can pass an array of indexes to this function below. So if you would like to get $some_array[0]['client_name']['third_level_index']
then you can do this:
function get_array_value(array $array, array $indexes)
{
if (count($array) == 0 || count($indexes) == 0) {
return false;
}
$index = array_shift($indexes);
if(!array_key_exists($index, $array)){
return false;
}
$value = $array[$index];
if (count($indexes) == 0) {
return $value;
}
if(!is_array($value)) {
return false;
}
return get_array_value($value, $indexes);
}
$some_array = array(/* nested array */);
$indexes = array(0, 'client_name', 'third_level_index');
$value = get_array_value($some_array, $indexes);
这篇关于PHP动态数组索引名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!