Reputation: 449
How can I convert text file into multidimensional array using php?
For example I have a text file as follows
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
I have to convert it to a multidimensional array to feed this data in a select box like
<optgroup label="Agriculture, Forestry, Fishing and Hunting
">
<option value=1>Crop Production</option>
....
</optgroup>
.....
How can I do this?
Regards, Rekha
Upvotes: 0
Views: 992
Reputation: 10603
$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>';
}
Upvotes: 1