开发者

PHP explode and put into array

开发者 https://www.devze.com 2023-01-21 03:32 出处:网络
I have this line of string Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie

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!


You can do:

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

Working link


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.


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);
}
0

精彩评论

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