开发者

convert text file into multidimensional array using php

开发者 https://www.devze.com 2023-03-28 05:18 出处:网络
How can I convert text file into multidimensional array using php? For example I have a text file as follows

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开发者_JAVA技巧
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


$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>';
 }
0

精彩评论

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