合并具有空字符串值的关联数组的数组以获取缺失键

Merging Arrays of Associative Arrays with Empty String Values for Missing Keys

我有两个具有不同键的关联数组。我需要将它们合并到一个关联数组的数组中,对于在更高索引处不存在的键,使用空值或空字符串。例如:

$first = array(array('x'=>'1','y'=>'2'));
$second = array(array('z'=>'3'),array('z'=>'4'));

结果应如下所示:

$result = array(
    array(
        'x'=>'1',
        'y'=>'2',
        'z'=>'3'
        ),
    array(
        'x'=>'',
        'y'=>'',
        'z'=>'4'
        )
    );

合并这些数组的函数需要能够处理两个或更多数组。这是我想出的:

// allArrays can be many arrays of all sizes and will be different each time this process runs
$allArrays = array($first, $second);
$longestArray = max($allArrays);
$data = array();
for($i = 0; $i < count($longestArray); ++$i) {
    $dataRow = array();
    foreach ($allArrays as $currentArray) {
        if (isset($currentArray[$i])) {
            foreach ($currentArray[$i] as $key => $value) {
                $dataRow[$key] = $value;
            }
        } else {
            foreach ($currentArray[0] as $key => $value) {
                $dataRow[$key] = '';
            } 
        }                
    }
    $data[] = $dataRow;
}

它有效,但我认为嵌套的 for 循环会导致大型数组的性能不佳,而且很难辨认。有没有更好的方法来解决这个问题?

不幸的是,这看起来是解决此问题的最佳方法。我会用上面的例子来回答这个问题,以防将来对任何人有帮助。

// allArrays can be many arrays of all sizes and will be different each time this process runs
$allArrays = array($first, $second);
$longestArray = max($allArrays);
$data = array();
for($i = 0; $i < count($longestArray); ++$i) {
    $dataRow = array();
    foreach ($allArrays as $currentArray) {
        if (isset($currentArray[$i])) {
            foreach ($currentArray[$i] as $key => $value) {
                $dataRow[$key] = $value;
            }
        } else {
            foreach ($currentArray[0] as $key => $value) {
                $dataRow[$key] = '';
            } 
        }                
    }
    $data[] = $dataRow;
}