0

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Hymed Ghenai
  • 199
  • 15

2 Answers2

2

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);
nice_dev
  • 17,053
  • 2
  • 21
  • 35
1

It is indirect programming to use a loop to merge-transpose your array data, then another loop to print to screen.

Ideally, you should try to merge these structures earlier in your code if possible (I don't know where these datasets are coming from, so I cannot advise.)

Otherwise, leave the two arrays unmerged and just write a single loop to print to screen. Because the two arrays are expected to relate to each other by their indexes, there will be no risk of generating Notices.

Since I am typing this out, I'll take the opportunity to reveal a couple of useful tricks:

  1. You can unpack your single-element subarrays by using array syntax with a static key pointing to the targeted variable in the foreach().
  2. Using printf() can help to cut down on line bloat/obfuscation caused by concatenation/interpolation. By writing placeholders (%s) into the string and then passing values for those placeholders in the trailing arguments, readablity is often improved.

Code: (Demo)

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

foreach ($sites as $index => ['title' => $title]) {
    printf(
        '%s - <a href="%s">See website</a></br>',
        $title,
        $links[$index]['link']
    );
}

Output:

Google - <a href="www.example1.com">See website</a></br>
Bing - <a href="www.example2.com">See website</a></br>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136