php - 来自两个逗号分隔的字符串 PHP 的 foreach 值
问题描述
我有两个字符串,其中包含有关国家和城市的信息
$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";
$city = explode(', ', $city);
$country = explode(', ', $country);
我知道如何通过单个数组进行 foreach。在下面的示例中,我正在通过国家/地区数组并添加 $value
foreach($country as $value)
{
$data[] = array (
"text" => $value,
"entities" => [
array (
"entity" => $city
)
]
);}
但无法弄清楚如何也合并 $city 数组并获得适当的值。例如,预期结果是
foreach($country as $value)
{
$data[] = array (
"text" => France,
"entities" => [
array (
"entity" => Paris
)
]
);}
解决方案
您选择一个数组并使用它来为循环播种,但同时处理这两个数组,假设它们是同步的。
以下是它如何与foreach
循环一起工作:
foreach ($country as $key => $value) {
$data[] = array(
"text" => $value,
"entities" => [
array(
"entity" => $city[$key],
),
]
);
}
这里有一个for
循环:
for($i = 0; $i < count($country); $i++){
$data[] = array(
"text" => $country[$i],
"entities" => [
array(
"entity" => $city[$i],
),
]
);
}
推荐阅读
- mysql - mysql创建一个由分隔数字组成的列
- powershell - 无法将 System.Object[] 转换为 {System.String, System.Management.Automation.ScriptBlock} 类型
- html - CSS选择表单元素内的输入
- sql - 在按三个字段排序的表上添加顺序索引
- linux - 如何在重定向后通过 wget 获取下载的文件名
- visual-studio - Visual Studio 中的格式化不会修复缩进
- python - 如何在电子邮件中将数据框附加为 excel 并从 python 发送该附件?
- java - 在 WhatApp 聊天中单击电子邮件链接时,如何让我的 Android 应用出现在应用选择器中
- sql - 如何从数据库中另一个表的 SELECT 查询中插入/更新表变量?
- reactjs - React Native Typescript:类型“string”不可分配给类型“solid”| “清楚” | “大纲”'.ts(2322)