从关联数组中提取值的子集 (php)
我想做一些看似非常简单的事情,但我找不到任何相关信息:只需提取类似于 array_splice 的数组子集,但使用键来检索值:
$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');
如果所有其他方法都失败,没有内置函数可以按键过滤关联数组吗? 例如:
$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'];
我想我想做第一个的原因是我不喜欢在我的整个系统中重复关联数组访问在代码中,将经常使用的值(例如在循环中)复制到局部变量中似乎会得到更好的优化,而且输入 $name 比输入 $somearray['name'] 容易得多。
编辑:谢谢,我想与列表一起使用,解决方案是对
list($x, $y, $z) = array_values(array_intersect_key($array, array_flip($wantedKeys)));
array_flip 的有趣使用!
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'];
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'].
EDIT: 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 use of array_flip!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这本质上与 SilentGhost 的答案相同,但这可能更容易,而且可能会慢一些。
This is essentially the same as SilentGhost's answer but this might be easier, and probably a little slower.
在 php 版本 >= 5.1.0 中,您可以使用
array_intersect_key
:中的值
$ex
并不重要,它们只需要存在即可。in php version >= 5.1.0 you could use
array_intersect_key
:values in
$ex
don't matter, they just have to be present.