views:

91

answers:

3

Hello,

I have this line of string

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

the : (colon) is the separator for the main topic, and the | is the separator for the different type of sub topics.

I tried to explode it out and put it into array, I need the result to be something like this to be displayed in a drop down menu:-

    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?
    }

Thanks!

+3  A: 

Code:

$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>";
 }

Updated to reflect the drop-down addition. Looks like I just did your homework, though I'll leave it up to you to combine all the into one foreach loop.

Jason
Thanks Jason! I do not need 3 drop down but your answer did help me to understand better:D
Sylph
I just realized that I have `$ilovefood[$cat[0]]` I don't actually love to each cats.
Jason
+3  A: 

You can do:

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

Working link

codaddict
Thanks for your answer. It works great!
Sylph
+1  A: 

I'd propose an arguably more readable version of 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);
}
meagar
Thank you! :) Solved my problem ;)
Sylph