php - Inefficient nested foreach loop

I have two array and want to merge it by using key of main array;

// $result        : main dataset (multidimensional array)
// $referenceData : data related with main dataset and want to merge it into main dataset (multidimensional array)

if ($result) {
    foreach ($result as $key => $val) {
        foreach ($referenceData[$val['id']] as $refKey => $refVal) {
            $result[$key][$refKey] = $refVal;
        }
    }
}

The thing is, when the result is high (even for 1000 elements on each) it takes more than 5-10 seconds which is quite unexpected for me.

I tried to use array_merge and array_merge_recursive instead of two foreach but I kept failing. Is there any way I could improve the logic? Thanks in advance.

Edit (added sample array);

result :

array(1) {
  [0]=>
  array(6) {
    ["id"]=>
    string(5) "13020"
    ["name"]=>
    string(23) "Data Stream 1"
    ["rank"]=>
    string(1) "3"
    ["data_1"]=>
    string(2) "63"
    ["data_2"]=>
    string(2) "256"
    ["data_3"]=>
    string(3) "469"
  }
}

referenceData:

array(1) {
  [13020]=>
  array(5) {
    ["percent"]=>
    float(20.987654320988)
    ["count_min"]=>
    string(1) "1"
    ["count_max"]=>
    int(2)
    ["checked"]=>
    bool(false)
    ["cond_id"]=>
    string(1) "0"
  }
}

Answer

Solution:

You need to make the first array structure exactly like the second array so that you can easily merge them. To do so you can do like below : (Its a reference code, you need to change it at your end)

$rows = $db->table('<table name>')->get()->getResultArray(); 
$result = []; 
foreach ($rows as $row) {      
    $result[$row['id']] = $row; 
}

Once both arrays have a similar structure, then you can go for a single foreach() and + operator to combine child arrays.

$finalArray = [];

foreach($result as $key=>$value){
    $finalArray[$key] = $value+$referenceData[$key];
}

print_r($finalArray);

Output: https://3v4l.org/qBa4V

Note: if you want to re-index this new array (in case you want indexes like 0,1,2... so on) then you can do:

$finalArray = array_values($finalArray);

Source