phparraysmultidimensional-arraygroupingassociative-array

Merge and flatten two 2d arrays to create an associative array with ids as keys and the latest date per id as values


I have two arrays:

Array 1 pulls from a CSV file.

[
    ["uid" => "cgajate", "date" => 20120918],
    ["uid" => "badrock5", "date" => 20120920],
    ["uid" => "ricoetc", "date" => 20120921],
    ["uid" => "ricoetc1", "date" => 20120923],
    ["uid" => "darbyfired", "date" => 20120922],
    ["uid" => "sagers.andrew", "date" => 20120922],
    ["uid" => "frankfurt9", "date" => 20120923],
    ["uid" => "beachboys", "date" => 20120923],
    ["uid" => "panterafan", "date" => 20120923],
    ["uid" => "kingsxrules", "date" => 20120923],
    ["uid" => "richard.bitto", "date" => 20120924],
    ["uid" => "christopher.boss", "date" => 20120925],
    ["uid" => "eric.robinson2", "date" => 20120926]
]

Array 2 pulls from the SQL database.

[
    ["uid" => "cgajate", "date" => 20120919],
    ["uid" => "ricoetc", "date" => 20120921],
    ["uid" => "ricoetc1", "date" => 20120922],
    ["uid" => "frankfurt9", "date" => 20120923],
    ["uid" => "beachboys", "date" => 20120923],
    ["uid" => "panterafan", "date" => 20120923],
    ["uid" => "kingsxrules", "date" => 20120923],
    ["uid" => "eric.robinson2", "date" => 20120926]
]

What I essentially want to do is build a flat associative array of unique uids and preserve the greater date when a uid occurs more than once.

Desired output:

[
  'cgajate' => 20120919,
  'badrock5' => 20120920,
  'ricoetc' => 20120921,
  'ricoetc1' => 20120923,
  'darbyfired' => 20120922,
  'sagers.andrew' => 20120922,
  'frankfurt9' => 20120923,
  'beachboys' => 20120923,
  'panterafan' => 20120923,
  'kingsxrules' => 20120923,
  'richard.bitto' => 20120924,
  'christopher.boss' => 20120925,
  'eric.robinson2' => 20120926
]

Solution

  • As PHP arrays are themselves hash maps, you could iterate through one array and insert each date into a new array, keyed by UID:

    $out = array();
    foreach ($first_array as $x) {
        $out[$x['uid']] = $x['date'];
    }
    

    Then, you could iterate through the second array, checking if any of the UIDs already exist as keys in the $out array. If the UID already exists, then you can compare dates and take whichever piece of data you prefer. For example, something like:

    foreach ($second_array as $y) {
        if (array_key_exists($y['uid'], $out)) {
            if ($out[$y['uid']] < $y['date']) {
                $out[$y['uid']] = $y['date'];
            }
        } else {
            $out[$y['uid']] = $date;
        }
    }
    

    Then, to flatten the data back down:

    $_out = array();
    foreach ($out as $uid => $date) {
        $_out[] = array("uid" => $uid, "date" => $date);
    }
    $out = $_out;