Taking 2 arrays and merging them together to output list

Hi there, I am trying to figure out how to take two arrays and intertwine them so that the following happens…

List1 = “London, Paris, New York”
List2 = “North, South, East, West”

and the output would be …

London, North
London, South
London, East
London, West
Paris, North
Paris, South
Paris, East
Paris, West
New York, North
New York, South
New York, East
New York, West

I wrote the following code but it doesnt seem to hit the mark unfortunately :frowning:


$keywordsarray 	= explode(",", "$sitedata[keywords]");
$locationsarray = explode(",", "$sitedata[locations]");

foreach ($keywordsarray as $keywordvalue) {    
    
	foreach ($locationsarray as $locationvalue) {
    		$locationsfull = "$keywordvalue $locationvalue,$locationsfull";
    		}
    
    $keywordsfull = "$locationsfull,$keywordsfull";
}

Ive not worked with arrays like this before so I’m getting a bit confused and was wondering if someone can spot where I’ve got wrong.

Many thanks,

Rik

You need to place a loop, in a loop. :slight_smile:

Take this for example:


<?php
foreach(array('London', 'Paris') as $city){
  foreach(array('North', 'East', 'South', 'West') as $direction){
    echo $city, ', ', $direction, PHP_EOL;
  }
}

/*
  London, North
  London, East
  London, South
  London, West
  Paris, North
  Paris, East
  Paris, South
  Paris, West
*/

If you wanted to add those to an array, it’s slightly different and a bit more like this:


<?php
$areas = array();
foreach(array('London', 'Paris') as $city){
  foreach(array('North', 'East', 'South', 'West') as $direction){
    array_push($areas, $city . ', ' . $direction);
  }
}

print_r(
 $areas
);

/*
  Array
  (
    [0] => London, North
    [1] => London, East
    [2] => London, South
    [3] => London, West
    [4] => Paris, North
    [5] => Paris, East
    [6] => Paris, South
    [7] => Paris, West
  )
*/

Does that make any sense?