Solvation Solvation - 1 year ago 72
PHP Question

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

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?

Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download