如何使用php将文本文件转换为多维数组?
例如,我有一个文本文件如下
1.Agriculture, Forestry, Fishing and Hunting
Crop Production
Oilseed and Grain Farming
Soybean Farming
Oilseed (except Soybean) Farming
Dry Pea and Bean Farming
Wheat Farming
Corn Farming
Rice Farming
Other Grain Farming
2.Animal Production
Cattle Ranching and Farming
Beef Cattle Ranching and Farming, including Feedlots
Beef Cattle Ranching and Farming
Cattle Feedlots
Dairy Cattle and Milk Production
Dairy Cattle and Milk Production
Dual-Purpose Cattle Ranching and Farming
Hog and Pig Farming
我必须将其转换为多维数组,以便在
之类的选择框中提供此数据<optgroup label="Agriculture, Forestry, Fishing and Hunting
">
<option value=1>Crop Production</option>
....
</optgroup>
.....
我该怎么做?
此致 雷卡
答案 0 :(得分:1)
$lines = file('your file.txt');
$groups = array();
foreach($lines as $ln)
{
if(preg_match("/^(\d+)\.(.*)$/", $ln,$m))
{
$groups[]['title'] = $m[2];
}
else
{
$groups[count($groups)-1]['options'][] = $ln;
}
}
/*** echo the optgroup and options ***/
foreach($groups as $i => $a)
{
echo '<optgroup label="'.$a['title'].'">';
foreach($a['options'] as $opt)
{
echo '<option>'.$opt.'</option>';
}
echo '</optgroup>';
}