首页 > 解决方案 > 来自两个逗号分隔的字符串 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
      )
      ]
);}   

标签: phparraysforeach

解决方案


您选择一个数组并使用它来为循环播种,但同时处理这两个数组,假设它们是同步的。

以下是它如何与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],
            ),
        ]
    );
}

推荐阅读