Search code examples
phparraysexplodetext-extractiondelimited

Print an array of pipe-delimited values as HTML list item tags


Data comes from Wordpress metabox in a form of single long array.

The data that I insert in metabox looks like this:

Rhine Riesling1|0,75 l|9,50 &euro

Rhine Riesling2|0,75 l|9,50 &euro

Rhine Riesling3|0,75 l|9,50 &euro

Rhine Riesling4|0,75 l|9,50 &euro

Final output should look like this:

<ul class="listmenuitems" id="listingmenu_1">
    <li><p>Rhine Riesling1 <span>0,75 l</span></p> <span class="listmenuprice">9,50 &euro;</span></li>
    <li><p>Rhine Riesling2 <span>0,75 l</span></p> <span class="listmenuprice">9,50 &euro;</span></li>
    <li><p>Rhine Riesling3 <span>0,75 l</span></p> <span class="listmenuprice">9,50 &euro;</span></li>
    <li><p>Rhine Riesling4 <span>0,75 l</span></p> <span class="listmenuprice">9,50 &euro;</span></li>
</ul>

How would I cut the array values into pieces considering the separator | and then loop through it to create a correctly formatted <li><p>?

I'm reading about PHP's explode() at the moment.


Solution

  • You can use the PHP explode command. http://php.net/manual/en/function.explode.php

    Loop through your array, on each entry call: explode("|", $entry); then you can print out what you want like so:

    $input_arr[];
    echo '<ul class="listmenuitems" id="listingmenu_1">';
    for($i=0;i<sizeof($input_arr);$i++) {
    
        $e = explode("|",$input_arr[$i]);
        echo "<li><p>" . $e[0] . "<span>" . $e[1] . "</span></p> <span class=\"listmenuprice\">" . $e[2] . "</span></li>";
    
    }
    

    Note there is on error checking and it is assumed that you have a complete and well formed array input.

    Updated to add foreach ;) And if the foreach loop is your fancy...

    $input_arr[];
    echo '<ul class="listmenuitems" id="listingmenu_1">';
    foreach($input_arr as $i) {
    
        $e = explode("|",$i);
        echo "<li><p>" . $e[0] . "<span>" . $e[1] . "</span></p> <span class=\"listmenuprice\">" . $e[2] . "</span></li>";
    
    }