PHP爆炸并放入数组

时间:2010-10-25 19:00:36

标签: php arrays multidimensional-array

我有这行字符串

Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie

:(冒号)是主要主题的分隔符,|是不同类型子主题的分隔符。

我试图将其爆炸并将其放入数组中,我需要将结果显示在下拉菜单中: -

    Fruits
      banana
      apple
      orange
    Food
      fries 
      sausages
    $result=explode(":",$data);
     foreach($result as $res) {
      $sub_res[]=explode("-",$res);

     }


     foreach($sub_res as $sub) {
      //echo $sub[1]."<br>"; Over here, I can get the strings of [0]=>banana|apple|orange, [1]=>sausages|fries, 
        // I explode it again to get each items 
            $items[]=explode("|",$sub[1]);
      $mainCategory[]=$sub[0]; // This is ([0]=>Fruits, ]1]=>Food, [2]=>dessert
            // How do I assign the $items into respective categories?
    }

谢谢!

3 个答案:

答案 0 :(得分:6)

你可以这样做:

$result=explode(":",$data);
foreach($result as $res) {
        $sub = explode("-",$res);
        $mainCategory[$sub[0]] = explode("|",$sub[1]);
}

Working link

答案 1 :(得分:3)

代码:

$data = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";
 foreach(explode(":",$data) as $res) { // explode by ":"
  $cat = explode("-",$res); // explode by "-"
  $ilovefood[$cat[0]] = explode("|",$cat[1]); // explode by "|"
 }
 print_r($ilovefood);
 //Returns : Array ( [Fruits] => Array ( [0] => banana [1] => apple [2] => orange ) [Food] => Array ( [0] => fries [1] => sausages ) [Desserts] => Array ( [0] => ice cream [1] => apple pie ) )
 foreach($ilovefood as $type=>$yum){
  echo "$type:<select>";
  foreach($yum as $tasty){
   echo "<option>$tasty</option>";
  }
  echo "</select>";
 }

更新以反映下拉添加。看起来我刚做完你的作业,不过我会把它留给你把所有的东西组合成一个foreach循环。

答案 2 :(得分:1)

我建议使用更具可读性的codeaddicts版本answer

$str = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";

$topics = array();
foreach (explode(':', $str) as $topic) {
  list($name, $items) = explode('-', $topic);
  $topics[$name] = explode('|', $items);
}