来自数组的PHP值,其中key位于另一个数组中

时间:2012-12-16 18:13:06

标签: php arrays

由于某种原因,我正在努力解决这个问题。

我有2个数组。第一个是名为colsArray的标准数组,如下所示:

Array
(
    [0] => fName
    [1] => lName
    [2] => city
)

第二个是名为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
    )

我只需要使用这两个数组来创建一个新数组,该数组包含来自query_data数组的所有数据,其中键位于第一个数组colsArray中。新数组看起来像这样:

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
    )
)

对此的任何帮助都会很棒。

谢谢!

2 个答案:

答案 0 :(得分:8)

PHP提供了一个variety of array functions,你通常只需要结合使用它们就可以了:

$keys = array_flip($colsArray);
$new_data = array();

foreach($query_data as $key => $data) {
    $new_data[$key] = array_intersect_key($data, $keys);
}

或者,功能更强大,但内存密集程度更高:

$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))
);

答案 1 :(得分:1)

$finalarr = [];
foreach ($query_data as $data) {
    $arr = [];
    foreach ($colsArray as $key){
       $arr[$key] = $data[$key];
    }
    $finalarr[] = $arr;
}

创建数组的[]表示法是新的,因此您可能不得不使用array()