I have as input a 2 dimensional array. Example:
$input = [
[1,2,3],
[11, "a" => "val_a"],
[12,'b' => 'val_b', 'a' => 'val2_a'],
[2 => 22]
];
I want to convert it to an array with a tabular structure. In the table-like structure, all sub-arrays (rows) have exactly the same key in the same order. These keys are the union of all keys of the 2nd level.
New Keys: [0, 1, 2, 'a', 'b']
Elements that do not exist in the input array receive the value NULL. I expect the following result:
$expected = [
[ 0 => 1, 1 => 2, 2 => 3, 'a' => NULL, 'b' => NULL],
[ 0 => 11, 1 => NULL, 2 => NULL, 'a' => "val_a", 'b' => NULL],
[ 0 => 12, 1 => NULL, 2 => NULL, 'a' => "val2_a", 'b' => "val_b"],
[ 0 => NULL, 1 => NULL, 2 => 22, 'a' => NULL, 'b' => NULL]
];
What I've tried so far:
function rectify($array){
$maxRow = [];
foreach($array as $row){
$maxRow += $row;
}
$new = [];
foreach($array as $key => $row){
foreach($maxRow as $mKey => $mVal){
$new[$key][$mKey] = array_key_exists($mKey,$row) ? $row[$mKey] : NULL;
}
}
return $new;
}
The function delivers correct results. The solution is very complex due to 2 nested loops with one query. Another attempt returned the same keys, but not in the same order.