0

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.

1
  • Side note: if you're looking for improvement for a working algorithm, Code review might be a better place. Commented Apr 9, 2021 at 16:57

1 Answer 1

2

This code first identifies all of the columns in the data. It then creates an empty template array (using array_unique to remove duplicates).

It then loops over the rows again and uses array_replace to fill the values in for each row...

$headers = [];
foreach ( $input as $row )  {
    $headers = array_merge($headers, array_keys($row));
}
$headers = array_fill_keys(array_unique($headers), null);
$output = [];
foreach ( $input as $row )  {
    $output[] = array_replace($headers, $row);
}
Sign up to request clarification or add additional context in comments.

1 Comment

array_replace is a good idea. Many Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.