Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用两个foreach循环优化PHP代码_Php - Fatal编程技术网

使用两个foreach循环优化PHP代码

使用两个foreach循环优化PHP代码,php,Php,我有一个由键组成的数组: $countries = ['EU', 'UK', 'Asia']; 另一个数组,包含基于这些键的其他元素: $countries_array=['UK'=>['London', 'Birmingham', 'Manchester'], 'EU'=> ['Germany','Netherlands'] , 'Asia'=> ['Pakistan','Bangladesh','China']]; $mid_countries[]; 我想遍历所有

我有一个由键组成的数组:

$countries = ['EU', 'UK', 'Asia'];  
另一个数组,包含基于这些键的其他元素:

$countries_array=['UK'=>['London', 'Birmingham', 'Manchester'], 'EU'=> ['Germany','Netherlands'] , 'Asia'=> ['Pakistan','Bangladesh','China']];

$mid_countries[];
我想遍历所有元素,检查它们是否为空,然后进一步创建另一个数组。我已经写了一个代码,它工作得很好。但它有foreach循环。有什么方法可以优化这段代码吗

foreach ($countries as $each_country) {
    if (!empty($countries_array["$each_country"][0])) {
        foreach ($countries_array["$each_country"] as $value) {
            $mid_countries[] = array("wildcard" => array("$each_country" => $value. "*"));
        }
    }
}
预期结果:

    array(8) { 
[0]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(8) "Germany*" } } [1]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(12) "Netherlands*"}} 
[2]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(7) "London*" } } [3]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Birmingham*" } } [4]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Manchester*" } } [5]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(9) "Pakistan*" } } [6]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(11) "Bangladesh*"}} 
[7]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(6) "China*" } } }
我想这是您所期望的(代码更新使用它在单循环中工作)


您的
$countries\u数组
包含语法错误。您的预期输出是什么?您的代码不应该工作。如果您能告诉我们如何进一步使用
$mid\u countries
,您可能根本不需要第二个foreach循环。现在我甚至看不到第一行。@vivek_23这是一个新数组,我需要在另一个PHP函数中进一步使用。我得到了数组到字符串转换通知,第一行。预期输出?给我一些例子?在问题中添加了它
foreach ($countries_array as $key=>$value) {         
   $tmp=implode('*#'.$key.'#',$value);
   $tmp='#'.$key.'#'.$tmp."*";
   $tmp=str_replace('#'.$key.'#',"\"}},{\"wildcard\":{\"".$key."\":\"",$tmp);
   $result=$result.substr($tmp,3)."\"}}"; 
}
$result="[".ltrim($result,"\"}},")."]";
$result=json_decode($result,true);
print_r($result);