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 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile