如何使用另一个数组通过键过滤数组 [英] How to filter an array by keys using another array
问题描述
我现在在我的项目上工作了几个小时,我从早期的阵列中获取了一些密钥,我想循环到我的新阵列,并从早期的阵列中选择我拥有的密钥的值.
I working now for a couple of hours on my project, i have some key's from a early array that i want to loop to my new array and pick the value of the key's that i have from the early array.
早期数组:
$old_keys = ['key1','key2','key3'];
新数组:
$result = ['key1' => 'foo', 'key2' => 'bar', 'key6' => 'ipsum'];
我想要的输出是:
$output = ['foo', 'bar'];
这就是我做的:
foreach ($old_keys as $old_key) {
$output[] = array_column($result, $old_key);
}
return $output;
我做错了什么,因为我得到的一切都是空数组
What did i wrong because everything what i get is a empty array
非常感谢!
更新:
$keys = array_flip($old_keys);
$output = array_values(array_intersect_key($result, $keys));
echo '<pre>';
var_dump($output);
现在$ output中填充了$ result的多维数组,但是值'foo'和'bar'在此多维数组的第二级中.问题是,我只能得到该数组的第一级,而不能得到第二级.
The $output is now filled with the multidimensional array of $result, but the values 'foo' and 'bar' are in the second level of this multidimensional array. The problem is, i get only the first level of this array and not the second level.
输出示例:
[
[0] => string
[1] => string
[
[key1] => foo
[key2] => bar
]
]
我想要的是:
[
[0] => string
[1] => string
[3] => foo
[4] => bar
]
解决方案:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($result)), true);
推荐答案
使用 $ old_keys
过滤 $ result
数组,但使用 $ old_keys
值作为键:
Filter the $result
array using $old_keys
, but use the $old_keys
values as keys:
$old_keys = array_flip(['key1','key2','key3']);
$result = ['key1' => 'foo', 'key2' => 'bar', 'key6' => 'ipsum'];
$output=array_intersect_key($result,$old_keys);
print_r($output);
如果要在结果中为键重新编制索引,请将 $ output
声明替换为:
If you want to re-index the keys in the result, replace the $output
declaration with:
$output=array_values(array_intersect_key($result,$old_keys));
这篇关于如何使用另一个数组通过键过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!