1

I have two strings that contain information about countries and cities

$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";

$city = explode(', ', $city);
$country = explode(', ', $country);

I know how to foreach trough single array. In the example below I am getting trough country array and add the $value

foreach($country as $value) 
{
$data[] = array (
    "text" => $value,
    "entities" => [
      array (
        "entity" => $city
      )
      ]
);}   

But cannot figure out how to also incorporate the $city array and get the appropriete value. For example, the expected result is

foreach($country as $value) 
{
$data[] = array (
    "text" => France,
    "entities" => [
      array (
        "entity" => Paris
      )
      ]
);}   
lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • 2
    Possible duplicate of [Two arrays in foreach loop](https://stackoverflow.com/questions/4480803/two-arrays-in-foreach-loop) – Nico Haase Oct 24 '19 at 08:19
  • Your expected result _really_ is an `entities` array that will only ever contain _one_ entity each? And _multiple_ items with `text => Germany` in $data? – 04FS Oct 24 '19 at 09:01

2 Answers2

2

You pick one array and use it to seed the loop, but process both at the same time on the assumption that they're in step.

Here is how it could work with a foreach loop:

foreach ($country as $key => $value) {
    $data[] = array(
        "text"     => $value,
        "entities" => [
            array(
                "entity" => $city[$key],
            ),
        ]
    );
}

And here with a for loop:

for($i = 0; $i < count($country); $i++){
    $data[] = array(
        "text"     => $country[$i],
        "entities" => [
            array(
                "entity" => $city[$i],
            ),
        ]
    );
}
Bananaapple
  • 2,984
  • 2
  • 25
  • 38
1

Since the size of the both arrays would be same, you can do it using one loop like this

$i=0;

foreach($country as $value) 
{
$data[] = array (
    "text" => $value,
    "entities" => [
      array (
        "entity" =>$city[$i++]; 
      )
      ]
);}  

While you are adding the country, keep adding the city using index on the city array.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78