dsbfbz75185 2017-02-02 16:32
浏览 46
已采纳

将关联数组的数组与缺少键的空字符串值合并

I have two arrays of associative arrays with different keys. I need to merge them into a single array of associative arrays, with nulls or empty strings for keys that do not exist at higher indices. For example:

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

The result should look like this:

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

The function that merges these arrays needs to be able to handle two or more arrays. Here's what I came up with:

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

It works, but I think the nested for loops cause poor performance on large arrays, and it's pretty illegible. Is there a better way to tackle this problem?

  • 写回答

1条回答 默认 最新

  • doutang1856 2017-02-07 15:15
    关注

    Unfortunately, it looks like this is the best way to solve this problem. I'll answer the question with the example from above in case it helps anyone in the future.

    // 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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用