phparraysmultidimensional-arraytext-parsingdelimited

Parse a string with three delimiters into an associative array of indexed arrays


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
...

Code:

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

Solution

  • You can do:

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

    Working link