phparraysarray-unique

How can I find all results in a PHP array, merge values, and then merge into another array


Using PHP, I have an array like this:

Array 1

[
  {epid: "123", hash: "xxxxxx"},
  {epid: "456", hash: "xxxxxx"},
  {epid: "789", hash: "xxxxxx"},
  {epid: "123", hash: "xxxxxx"},
  {epid: "123", hash: "xxxxxx"},
]

Then, I have a second array like this:

Array 2

[
  {epid: "123", name: "This is a title"},
  {epid: "456", name: "This is a title"},
  {epid: "789", name: "This is a title"}
]

My goal is to get all hash from array one and add them to the appropriate record in array 2. From this example, the results would be:

[
  {epid: "123", name: "This is a title", hash: [ xxxxxx, xxxxxx, xxxxxx ] },
  {epid: "456", name: "This is a title", hash: [ xxxxxx ] },
  {epid: "789", name: "This is a title", hash: [ xxxxxx ] }
]

I'm sure there are multiple loops here, but for the life of me, I can't wrap my brain around it.


Solution

  • You could loop through the second array and use the epid to find the indexes in the first array. Then for every index found, add the hash to the current loop item:

    $lookup = [
        ["epid" => "123", "hash" => "xxxxxxA"],
        ["epid" => "456", "hash" => "xxxxxxB"],
        ["epid" => "789", "hash" => "xxxxxxC"],
        ["epid" => "123", "hash" => "xxxxxxD"],
        ["epid" => "123", "hash" => "xxxxxxE"],
    ];
    
    $db = [
        ["epid" => "123", "name" => "This is a title"],
        ["epid" => "456", "name" => "This is a title"],
        ["epid" => "789", "name" => "This is a title"]
    ];
    
    foreach($db as $i => $el) {
        $keys = array_keys(array_column($lookup, 'epid'), $el["epid"]);
        foreach($keys as $key) {
            $db[$i]["hash"][] = $lookup[$key]["hash"];
        }
    }
    
    var_dump($db);