我想要做的是通过/,/来爆炸来自MySQL的一些字符串,然后以某种方式能够在循环之外引用这些数组。
这是因为,每个地区,国家和地区都以适当的顺序列在$ data数组中,我需要以某种方式将它们粘合在一起。
例如,在MySQL内部有一个字符串存储为:
Regions: Africa, Balkans, South America
Countries: Uganda, Greece, Brazil
Provinces: Ubuge, Athenos, Santa Catarina
但是我很难想象如何将这些组合在一起,请记住,有时每个阵列中只有一个成员,或者最多可以有一个成员。但每个数组总是包含相同的数字。
我的尝试是这样的......我可以让它们像这样打印,但我无法保存它们以便在循环之外使用。
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;
}
}
任何想法或帮助都将不胜感激。
我希望最终产品看起来像
地点:
Africa --- Uganda --- Ubuge
Balkans --- Greece --- Athenos
South America --- Brazil --- Santa Catarina
答案 0 :(得分:1)
嗯,如果我理解你的问题,关联数组可能是一个很好的解决方案:
$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']}";
}
答案 1 :(得分:0)
db重新设计可行:
区域
id |区域
国家
id |国家|的region_id
省
id |省| COUNTRY_ID