开发者

How to give a unique name to elements of foreach outside of the loop?

What I am trying to do is explode some strings from MySQL by /,/, and then somehow be able to refer to these arrays outside of the loop.

This is because, each region, country and province are listed in the $data array in the appropriate order, and I need to glue them together somehow.

For example, inside MySQL there is a string stored as:

Regions: Africa, Balkans, South America
Countries: Uganda, Greece, Brazil
Provinces: Ubuge, Athenos, Santa Catarina

But I am having a really hard time trying to imagine how to tie these together, remember that sometimes there is only one member in each array, or there can be up to a hundred. But each array always contains the same number.

My attempt is something like this... I can get them to print like this, but I can't save them to use outside of the loop.

  for ($i = 0; $i < $numrows; $i++){

            $provinces = explode(',', $data[$i]['provinces']) ;
            $countries = explode(',', $data[$i]['countries']) ;
            $regions = explode(',', $data[$i]['regions']) ;       

            foreach($countries as &$country){

            echo $country;

                }
}

Any ideas or help would be appreciated.

What I would like to have the final product look like would be

Place:

Africa --- Uganda --- Ubuge
Balkans --- 开发者_开发问答Greece --- Athenos
South America --- Brazil --- Santa Catarina


Hmm, an associative array might be a good solution for this, if I understand your issue:

$region_list = array();

for ($i = 0; $i < $numrows; $i++){    
     $provinces = explode(',', $data[$i]['provinces']) ;
     $countries = explode(',', $data[$i]['countries']) ;
     $regions = explode(',', $data[$i]['regions']) ;       

     // So we don't have to run count every time in the loop
     $length = count($countries);

     // Since it's based of the same numeric index
     for($j = 0; $j < $length; $j++)
        $region_list[$regions[$j]] = array(
          'province' => $provinces[$j],
          'country' => $countries[$j]);
     }
}

// Now to loop through all our data
// For an associative array, we can loop over key => value so $region
// becomes the region name
foreach($region_list as $region => $data) {
   echo "$region --- {$data['country']} --- {$data['province']}";
}


db redesign that would work:

regions
id | region

countries
id | country | region_id

Provinces
id | province | country_id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜