处理一个数组,使其始终包含另一个数组值中的键(和顺序)


Process an array to always contain keys (and order) from values of another array

我有以下"键"数组:(数组1)

Array
(
    [0] => first_name
    [1] => surname
    [2] => position
    [3] => age
)

此数组应确定数组2中应存在的键和键/值的顺序。因此,在一个完美的世界里,阵列2看起来是这样的:

Array
(
    [0] => Array
        (
            [first_name] => James
            [surname] => Johnstone
            [position] => Striker
            [age] => 42
        )
    [1] => Array
        (
            [first_name] => Al
            [surname] => MacLean
            [position] => Defender
            [age] => 22
        )
    ...
)

我遇到的问题在下面的示例数组中。有时:

a) 数组2中键的顺序与数组1不同
b) 数组1中定义的一些密钥在数组2中不存在,比如

Array
(
    [0] => Array
        (
            [position] => Defender
            [first_name] => James
            [surname] => McDonald
        )
    [1] => Array
        (
            [position] => Striker
            [first_name] => Ben
            [surname] => Lailey
        )
    ...
)

我想要一些帮助来创建一个PHP函数,它将接受一个"格式错误"的数组2,比如上面的数组,并将其转换为应该的样子:按数组1定义的顺序,并添加任何丢失的键以变得"正确",比如:

Array
(
    [0] => Array
        (
            [first_name] => James
            [surname] => McDonald
            [position] => Defender
            [age] => 
        )
    [1] => Array
        (
            [first_name] => Ben
            [surname] => Lailey
            [position] => Striker
            [age] =>
        )
    ...
)

本例中使用的密钥是任意的,数组1中可能添加、删除或重新排序了一个新密钥,我需要数组2来尊重数组1。

提前谢谢。

一个简单的实现:

// Pass in an array of keys, and an array of arrays
function cleanArray($keys, $arrays)
{
    // Create an empty container for our final output
    $final = array();
    // Loop through array of arrays
    foreach($arrays as $a)
    {
        // Create empty value for current item
        $next = array();
        // Loop through keys, in order
        foreach($keys as $k)
        {
            // Assign next key and value if we have it, or a blank string if we don't
            $next[$k] = isset($a[k]) ? $a[k] : '';
        }
        // Add current item to output
        $final[] = $next;
    }
    // Return final values, each item now having its keys ordered and normalized
    return $final;
}

尝试使用数组键exists函数http://php.net/manual/en/function.array-key-exists.php

如果不存在,则添加一个缺少键的空元素。(您不关心关联数组中的顺序)

$new=array();    
foreach ($array2 as $a2){
  foreach($array1 as $k1=>$a1){
  $new[][$k1]=$a2[$k1];
  } 
}