Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode and put into array

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!

like image 902
Sylph Avatar asked Oct 25 '10 19:10

Sylph


3 Answers

You can do:

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

Working link

like image 100
codaddict Avatar answered Oct 03 '22 04:10

codaddict


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.

like image 33
Jason Avatar answered Oct 03 '22 03:10

Jason


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);
}
like image 42
meagar Avatar answered Oct 03 '22 03:10

meagar