从关联数组中提取值的子集(PHP) [英] Extracting a subset of values from an associative array (php)
问题描述
我想要做一些看似很简单,但我无法找到任何关于它:简单地提取相似的阵列array_splice的一个子集,但是的使用键来检索值的:
I want to do something seemingly very simple, but I can't find anything about it: simply extract a subset of an array similar to array_splice, but using keys to retrieve the values :
$data = array('personName' => 'John', 'personAge' => 99, 'personId' => 1,
/* many more data I don't need here ... */);
list($name, $age, $id) = array_splice_by_keys($data,
array('personName', 'personAge', 'personId');
如果一切都失败了,是不是有一个内置函数,以滤除键关联数组?例如:
If all else fails, isn't there a builtin function to filter an associative array by keys? For example:
$ filteredArray = array__extract__keys__and__values($ srcArray,$ arrayOfWantedKeys);
// create a new array with ONLY those key => values I need
$wanted_values = array_extract_keys_and_values($data,
array('personName', 'personAge', 'personId');
echo $wanted_values['personName'];
我想,为什么我想要做的第一个原因,就是我不喜欢重复关联数组访问都在我的code,它似乎更好地优化复制时使用了大量的数值(在例如环),在局部变量,再加上它更容易输入$命名超过$的someArray ['名']。
I guess the reason why I want to do the first one, is that I don't like to repeat associative array access all over my code, it would seem better optimized to copy the values that are used a lot (in a loop for example), into a local variable, plus it's much easier to type $name than $somearray['name'].
编辑:谢谢,我想与列表的使用,解决办法是
Thanks, I guess for use with list, the solution would be
list($x, $y, $z) = array_values(array_intersect_key($array, array_flip($wantedKeys)));
Intesresting使用array_flip的!
Intesresting use of array_flip!
推荐答案
在PHP版本> = 5.1.0可以使用的 array_intersect_key
:
in php version >= 5.1.0 you could use array_intersect_key
:
$data = array('personName' => 'John', 'personAge' => 99, 'personId' => 1,
'test' => 23);
$ex = array('personName'=>0, 'personAge'=>0, 'personId'=>0);
var_dump(array_intersect_key($data, $ex));
在 $前值
并不重要,他们只需要为present。
values in $ex
don't matter, they just have to be present.
这篇关于从关联数组中提取值的子集(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!