Reputation: 1339
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
)
]
);}
Upvotes: 1
Views: 85
Reputation: 12401
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.
Upvotes: 1
Reputation: 3114
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],
),
]
);
}
Upvotes: 2