Search code examples
phparraysmultidimensional-arraymergetranspose

How to merge two arrays into one and transpose the structure to simplify printing from a loop?


How can I combine 2 arrays ... :

$array_1 = [['title' => 'Google'], ['title' => 'Bing']];

$array_2 = [['link' => 'www.example1.com'], ['link' => 'www.example2.com']];

In order to get ... :

$array_3 = [
    ['title' => 'Google', 'link' => 'www.example1.com'],
    ['title' => 'Bing', 'link' => 'www.example2.com']
];

I guess $array_3 should be structured the following way in order to get :

Final result:

Google - See website

Bing - See website

The function to get the final result:

function site_and_link($array_3) {
    foreach ($array_3 as $a) {
        echo $a['title'] . " - <a href=" . $a['link'] . ">See website</a></br>";
    }
}

What is the missing step to arrange $array_3?


Solution

  • You can use a simple foreach loop and array_merge to merge both subarrays.

    <?php
    
    $result = [];
    foreach($array_1 as $index => $val){
      $result[] = array_merge($val,$array_2[$index]);
    }
    
    print_r($result);