【问题标题】:Merging Arrays of Associative Arrays with Empty String Values for Missing Keys将关联数组的数组与缺失键的空字符串值合并
【发布时间】:2017-02-02 16:32:45
【问题描述】:

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

$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 循环会导致大型数组的性能不佳,而且非常难以辨认。有没有更好的方法来解决这个问题?

【问题讨论】:

  • 有几个数组的合并内置函数可能会帮助您并使您的生活更轻松,请在手册中查看它们。
  • @SanderBackus,他的结果比 array_merge_recursive PHP 函数结果更复杂
  • 我检查了 array_merge_recursive 和其他内置插件,但我要么没有找到正确的组合方式,要么它们并不能完全解决我的问题。

标签: php arrays associative-array


【解决方案1】:

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

// 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2017-01-13
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多