简体   繁体   中英

Optimizing PHP code with two foreach loops

I have an array that consists of the keys:

$countries = ['EU', 'UK', 'Asia'];  

Another array that consists of further elements based on those keys:

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

$mid_countries[];

I want to pass through all the elements, check if they are empty or not and then further create another array. I have written a code and it works fine. But it has foreach loops. Is there any way that I could optimize this code?

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. "*"));
        }
    }
}

Expected result:

    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*" } } }

I think you expected this (Code updated use its working in single loop)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM