[英]PHP values from array where key is in another array
I am struggling with this for some reason. 由于某种原因,我为此感到挣扎。
I have 2 arrays. 我有2个数组。 The first is a standard array called colsArray that looks like this:
第一个是称为colsArray的标准数组,如下所示:
Array
(
[0] => fName
[1] => lName
[2] => city
)
The second is a multidimensional array called query_data that looks like this: 第二个是称为query_data的多维数组,如下所示:
Array
(
[0] => Array
(
[recordID] => xxx
[fName] => xxx
[lName] => xxx
[address1] => xxx
[city] => xx
[zip] => xxx
[vin] => xxx
)
[1] => Array
(
[recordID] => xxx
[fName] => xxx
[lName] => xxx
[address1] => xxx
[city] => xxx
[zip] => xxx
[vin] => xxx
)
[2] => Array
(
[recordID] => xxx
[fName] => xxx
[lName] => xxx
[address1] => xxx
[city] => xxx
[zip] => xxx
[vin] => xxx
)
[3] => Array
(
[recordID] => xxx
[fName] => xxx
[lName] => xxx
[address1] => xxx
[city] => xxx
[zip] => xxx
[vin] => xxx
)
) )
I just need to use those 2 arrays to create a new array that has all the data from the query_data array where the keys are in the fist array colsArray. 我只需要使用这2个数组来创建一个新数组,该数组具有来自query_data数组的所有数据,其中键位于第一数组colsArray中。 The new array would look like this:
新数组如下所示:
Array
(
[0] => Array
(
[fName] => xxx
[lName] => xxx
[city] => xx
)
[1] => Array
(
[fName] => xxx
[lName] => xxx
[city] => xx
)
[2] => Array
(
[fName] => xxx
[lName] => xxx
[city] => xx
)
[3] => Array
(
[fName] => xxx
[lName] => xxx
[city] => xx
)
)
Any help on this would be great. 任何帮助都会很棒。
Thanks! 谢谢!
PHP offers a variety of array functions , and you usually get away with just combining a bunch of those: PHP提供了各种数组函数 ,通常只需组合其中的一堆即可:
$keys = array_flip($colsArray);
$new_data = array();
foreach($query_data as $key => $data) {
$new_data[$key] = array_intersect_key($data, $keys);
}
Alternatively, a more functional style, but more memory intensive: 另外,一种更实用的样式,但更多的内存消耗:
$new_data = array_map(
'array_intersect_key', // or just array_intersect_key in newer PHP versions
$query_data,
array_pad(array(), count($query_data), array_flip($colsArray))
);
$finalarr = [];
foreach ($query_data as $data) {
$arr = [];
foreach ($colsArray as $key){
$arr[$key] = $data[$key];
}
$finalarr[] = $arr;
}
The []
notation for creating arrays is new, so you might have to use array()
instead. 用于创建数组的
[]
表示法是新的,因此您可能不得不使用array()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.